-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path19-conditional-types.ts
88 lines (75 loc) · 1.72 KB
/
19-conditional-types.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// ======== filter types from union which fulfill constraint
{
type Client = {
name: string;
budget: number;
};
type Employee = {
firstName: string;
surname: string;
};
type Companies = {
name: string;
};
type Response = Client | Employee | Companies;
// get only types which has `name` property
type OnlyWithName<T> = T extends { name: string } ? T : never;
type ClientsFilter = OnlyWithName<Response>;
}
// ========= get only strings from type ==========
{
type ClientModel = {
id: number;
name: string;
budget: number;
};
type OnlyStringsFields<T> = {
[OnlyStringKey in {
[Key in keyof T]: T[Key] extends string ? Key : never;
}[keyof T]]: T[OnlyStringKey];
};
type OnlyStringsFromClient = OnlyStringsFields<ClientModel>;
/**
* Result type:
* type OnlyStringsFromClient = {
name: string;
}
*/
}
// ========= create type which fields fulfill constraint ==========
{
type ClientModel = {
id: number;
name: string;
budget: number;
address: {
city: string;
street: string;
};
correspondenceAddress: {
city: string;
street: string;
postOffice: string;
};
};
type FulfillConstraint<T, TConstraint> = {
[OnlyStringKey in {
[Key in keyof T]: T[Key] extends TConstraint ? Key : never;
}[keyof T]]: T[OnlyStringKey];
};
type OnlyStringsFromClient = FulfillConstraint<ClientModel, { city: string }>;
/** Result type
* type OnlyStringsFromClient = {
address: {
city: string;
street: string;
};
correspondenceAddress: {
city: string;
street: string;
postOffice: string;
};
}
*/
}
export {};