-
Notifications
You must be signed in to change notification settings - Fork 0
/
11 ~ Conditional Types.ts
109 lines (97 loc) · 1.88 KB
/
11 ~ 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// "If-else"
type DayPlanning<Day> = Day extends "Saturday" | "Sunday"
? {
toEat: string
relaxingActivity: string
}
: {
toEat: string
workItemToDo: string
}
type Day =
| "Monday"
| "Tuesday"
| "Wednesday"
| "Thursday"
| "Friday"
| "Saturday"
| "Sunday"
type WeekPlanning = {
[TDay in Day]: DayPlanning<TDay>
}
/*
*
*
*
*/
type UserUnion =
| {
type: "LoggedIn"
userName: string
}
| {
type: "LoggedOut"
}
type GetUserName = <U extends UserUnion>(
user: U
) => U["type"] extends "LoggedIn" ? string : undefined
// This way we say we have a variable of this type
declare const getUserName: GetUserName
const a = getUserName({ type: "LoggedIn", userName: "Jens" })
a
// ^?
const b = getUserName({ type: "LoggedOut" })
b
// ^?
/*
*
*
*
*/
type Company = {
companyName: string
hiring: boolean
founded: Date
}
type StringifiedCompany = {
[Key in keyof Company]: Company[Key] extends boolean
? "true" | "false"
: Company[Key] extends Date
? string
: Company[Key]
}
/*
*
*
*
*/
// What if we "call" a generic/conditional with a union?
// Make sure to also read the "Errata" file!
type NumberOrString<T> = T extends "foo"
? number
: T extends "bar"
? string
: never
type A = NumberOrString<"foo">
type B = NumberOrString<"bar">
type C = NumberOrString<"qux">
type D = NumberOrString<"foo" | "bar">
type E = NumberOrString<"bar" | "foo">
type F = NumberOrString<"foo" | "qux">
type G = NumberOrString<"bar" | "qux">
type H = NumberOrString<"foo" | "bar" | "qux">
/*
*
*
*
*/
type NumberInUnit<Unit> = {
value: number
unit: Unit
}
type InKiloGrams = NumberInUnit<"kilogram">
type InPounds = NumberInUnit<"pound">
type Weight = NumberInUnit<"kilogram" | "pound">
type Weight2 = NumberInUnit<"kilogram"> | NumberInUnit<"pound">
type Weight3 = InKiloGrams | InPounds
// See also the Errata!