Skip to content

Commit

Permalink
Add RequireAtLeastOne type
Browse files Browse the repository at this point in the history
  • Loading branch information
CvX committed Mar 13, 2019
1 parent aea4f4d commit 85275d4
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
23 changes: 23 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,26 @@ const ab: Merge<Foo, Bar> = {a: 1, b: 2};
```
*/
export type Merge<FirstType, SecondType> = Omit<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;

/*
Create a type that requires at least one of the given keys.
@example
```
import {RequireAtLeastOne} from 'type-fest';
type SystemMessages = {
macos?: string;
linux?: string;
windows?: string;
default?: string;
};
const messages: RequireAtLeastOne<SystemMessages, 'macos' | 'linux' | 'windows'> = {macos: 'hey', default: 'hello'};
```
*/
export type RequireAtLeastOne<T, Keys extends keyof T = keyof T> =
Omit<T, Keys>
& {
[Key in Keys]-?: Required<Pick<T, Key>>
}[Keys];
1 change: 1 addition & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable import/no-unassigned-import */
import './test/omit';
import './test/merge';
import './test/require-at-least-one';

// TODO: Add negative tests. Blocked by: https://github.com/SamVerschueren/tsd-check/issues/2
22 changes: 22 additions & 0 deletions test/require-at-least-one.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {RequireAtLeastOne} from '..';

type SystemMessages = {
macos?: string;
linux?: string;
windows?: string;
default?: string;
};

type ValidMessages = RequireAtLeastOne<SystemMessages, 'macos' | 'linux' | 'windows'>;
const test = (_: ValidMessages[]): void => {};

test([
{macos: 'hey'},
{macos: 'hey', default: 'hello'},
{linux: 'sup', windows: 'hi'},
{macos: 'hey', linux: 'sup', windows: 'hi', default: 'hello'}

// Negative examples:
// {},
// {default: 'hello'},
]);

0 comments on commit 85275d4

Please sign in to comment.