0%

Typescript - Type Guard

每次都要用as強制型別轉換?

1
2
3
4
5
6
7
8
enum Gender {
MALE = 'male',
FEMALE = 'female'
}

const foo = (gender = 'male' as Gender) => {
return Object.values(Gender).includes(gender);
}

Sol 1 Type Guard

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
enum Gender {
MALE = 'male',
FEMALE = 'female'
}

const isGender = (gender: any): gender is Gender => {
return Object.values(Gender).includes(gender);
}

const foo = (gender = 'male') => {
if(isGender(gender)) {
// .includes(gender) // gender 的型別是Gender
return Object.values(Gender).includes(gender);
}
}
  • 額外補充 「Narrowing」

Sol 2 Generics

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
enum Gender {
MALE = 'male',
FEMALE = 'female'
}

enum Gender_2 {
MALE = 'male',
FEMALE = 'female'
}

const mapper = {
[Gender_2.MALE]: Gender.MALE,
[Gender_2.FEMALE]: Gender.FEMALE
}

const createMapper = <T>(mapping: T) => (value: keyof T | null): T[keyof T] | undefined => {
return value === null ? undefined : mapping[value];
}

const foo = (gender: Gender_2.MALE) => {
const data = { gender: Gender.MALE };
const getMapper = createMapper(mapper);
const trans = getMapper(gender);

return trans === data.gender;
}

Reference

Typescript 一些令人又愛又恨的內容 — Type Guard、Narrowing