-
-
Notifications
You must be signed in to change notification settings - Fork 550
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import type {UnionToIntersection} from './union-to-intersection'; | ||
|
||
/** | ||
Convert a union type into a tuple/array type of its elements. | ||
This can be useful when you have objects with a finite set of keys and want a type defining only the allowed keys, but do not want to repeat yourself. | ||
@example | ||
``` | ||
const pets = { | ||
dog: '🐶', | ||
cat: '🐱', | ||
snake: '🐍', | ||
}; | ||
type Pet = keyof typeof pets; | ||
//=> "dog" | "cat" | "snake" | ||
const petList = Object.keys(pets) as UnionToTuple<Pet>; | ||
//=> ["dog", "cat", "snake"] | ||
``` | ||
@category Array | ||
*/ | ||
|
||
export type UnionToTuple<Tuple> = UnionToIntersection< | ||
Tuple extends never ? never : (_: Tuple) => Tuple | ||
> extends (_: never) => infer LastTupleElement | ||
? [...UnionToTuple<Exclude<Tuple, LastTupleElement>>, LastTupleElement] | ||
: []; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
import {expectAssignable, expectError, expectType} from 'tsd'; | ||
import type {UnionToTuple} from '../index'; | ||
|
||
type Options = UnionToTuple<'a' | 'b' | 'c'>; | ||
|
||
const options: Options = ['a', 'b', 'c']; | ||
|
||
expectAssignable<Options>(options); | ||
expectType<'a'>(options[0]); | ||
expectType<'b'>(options[1]); | ||
expectType<'c'>(options[2]); | ||
expectError(options[0] = 'b'); |