-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04 ~ Discriminated Union.ts
59 lines (54 loc) · 1000 Bytes
/
04 ~ Discriminated Union.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
type DiceEyes = 1 | 2 | 3 | 4 | 5 | 6
type Suit = "Hearts" | "Diamond" | "Spade" | "Clubs"
enum DiceEyesAsEnum {
One = 1,
Two,
Three,
Four,
Five,
Six,
}
enum SuitAsEnum {
Hearts = "H",
Diamond = "D",
Spade = "S",
Clubs = "C",
}
/*
*
*
*
*/
export type UserUnion =
| {
type: "LoggedIn"
user: {
name: string
}
}
| {
type: "LoggedOut"
}
const anonymous: UserUnion = { type: "LoggedOut" }
const user: UserUnion = { type: "LoggedIn", user: { name: "Homer" } }
/*
*
*
*
*/
const unreachable = (_arg: never) => {
throw new Error("Should not be reachable")
}
const getUserNameLength = (userUnion: UserUnion) => {
switch (userUnion.type) {
case "LoggedOut":
return 0
case "LoggedIn":
// We can correctly access userUnion.user here
return userUnion.user.name.length
default:
// If we comment out one of the branches above
// we get a type error
return unreachable(userUnion)
}
}