forked from wesbos/hot-tips
-
Notifications
You must be signed in to change notification settings - Fork 0
/
type-narrowing.ts
51 lines (35 loc) · 1.07 KB
/
type-narrowing.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
type Success = { message: string; value: number }
type Failure = { message: string; error: string }
type Response = Success | Failure
const responses: (Success | Failure)[] = [
{ message: 'Success', value: 69 },
{ message: 'Failure', error: 'shoot' },
{ message: 'Success', value: 777 },
]
//· only Success has a value property. Narrow it down!
const response = responses[0];
// Using `in` works. checks up the prototype chain
if('value' in response) {
response.value;
// ^?
}
// hasOwnProperty() doesn't. (only checks instance)
if (response.hasOwnProperty('value')) {
response.value;
// ^?
}
// Type Guard with Predicate works
function isSuccess(response: Response): response is Success {
return response.hasOwnProperty('value');
}
if (isSuccess(response)) {
response.value;
// ^?
}
const successes = responses
.filter(response => response.hasOwnProperty('value'))
.map(response => response.value);
const successes2 = responses
.filter((response): response is Success => response.hasOwnProperty('value'))
.map(response => response.value);
export{}