UNPKG

725 BTypeScriptView Raw
1/**
2Create a union of all keys from a given type, even those exclusive to specific union members.
3
4Unlike the native `keyof` keyword, which returns keys present in **all** union members, this type returns keys from **any** member.
5
6@link https://stackoverflow.com/a/49402091
7
8@example
9```
10import type {KeysOfUnion} from 'type-fest';
11
12type A = {
13 common: string;
14 a: number;
15};
16
17type B = {
18 common: string;
19 b: string;
20};
21
22type C = {
23 common: string;
24 c: boolean;
25};
26
27type Union = A | B | C;
28
29type CommonKeys = keyof Union;
30//=> 'common'
31
32type AllKeys = KeysOfUnion<Union>;
33//=> 'common' | 'a' | 'b' | 'c'
34```
35
36@category Object
37*/
38export type KeysOfUnion<ObjectType> = ObjectType extends unknown
39 ? keyof ObjectType
40 : never;