UNPKG

1.29 kBTypeScriptView Raw
1import type {IsNever} from './is-never';
2import type {UnionToIntersection} from './union-to-intersection';
3
4/**
5Returns the last element of a union type.
6
7@example
8```
9type Last = LastOfUnion<1 | 2 | 3>;
10//=> 3
11```
12*/
13type LastOfUnion<T> =
14UnionToIntersection<T extends any ? () => T : never> extends () => (infer R)
15 ? R
16 : never;
17
18/**
19Convert a union type into an unordered tuple type of its elements.
20
21"Unordered" means the elements of the tuple are not guaranteed to be in the same order as in the union type. The arrangement can appear random and may change at any time.
22
23This 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.
24
25@example
26```
27import type {UnionToTuple} from 'type-fest';
28
29type Numbers = 1 | 2 | 3;
30type NumbersTuple = UnionToTuple<Numbers>;
31//=> [1, 2, 3]
32```
33
34@example
35```
36import type {UnionToTuple} from 'type-fest';
37
38const pets = {
39 dog: '🐶',
40 cat: '🐱',
41 snake: '🐍',
42};
43
44type Pet = keyof typeof pets;
45//=> 'dog' | 'cat' | 'snake'
46
47const petList = Object.keys(pets) as UnionToTuple<Pet>;
48//=> ['dog', 'cat', 'snake']
49```
50
51@category Array
52*/
53export type UnionToTuple<T, L = LastOfUnion<T>> =
54IsNever<T> extends false
55 ? [...UnionToTuple<Exclude<T, L>>, L]
56 : [];