-
Notifications
You must be signed in to change notification settings - Fork 0
/
UtilityTypes.ts
58 lines (49 loc) · 1.42 KB
/
UtilityTypes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/** Tries to match the TS's builtin string `enum` type (e.g. `typeof Enum`) */
export type EnumString = { [key: string]: string };
export type KeysOfUnion<T> = T extends T ? keyof T: never;
/**
* Accepts a value from `TEnum` as an enum key (e.g. `Enum.Foo`),
* or as a string literal (e.g. 'Foo').
*
* ### Example
* ```
* enum E { Foo, Bar }
* let x: EnumValuesLiteral<E>;
*
* x = E.Foo;
* x = E.Bar;
*
* x = 'Foo';
* x = 'Bar';
* ```
*/
export type EnumValuesLiteral
<TEnum extends string> = TEnum | `${TEnum}`;
/**
* Accepts a specific key from `TEnum` either as a enum key (e.g. `Enum.Foo`),
* or as a string literal (e.g. 'Foo').
*
* A less brittle way of writing `Enum.Foo | 'Foo'` (i.e. because the keys will be in sync
* when renaming an enum entry, or error when given an invalid key).
*
* ### Example
* ```
* enum E { Foo, Bar }
* let x: EnumValueLiteral<typeof E, 'Foo'>;
*
* x = E.Foo;
* x = 'Foo';
*
* x = E.Bar // error
* x = 'Bar' // error
*
* let z: EnumValueLiteral<typeof E, 'Baz'>; // error
* ```
*/
export type EnumValueLiteral
<TEnum extends EnumString, TKey extends keyof TEnum> = TKey | TEnum[TKey];
export type KeyMapType
<T extends string, K extends { [k in `${T}`]: any }> = K;
export type NeverUndefined<T> = T extends undefined | null ? never : T;
/** Can be either `null` or `undefined` (it doesn't really matter). */
export type Nullish<T> = T | null | undefined;