-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path类型守卫.ts
47 lines (43 loc) · 998 Bytes
/
类型守卫.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
/**
* JavaScript实现
* @param strOrArray
* @returns
*/
{
const convertToUppercase = strOrArray =>{
if(typeof strOrArray === 'string'){
return strOrArray.toUpperCase()
} else if(Array.isArray(strOrArray)){
return strOrArray.map(item=>item.toUpperCase())
}
}
}
{
const convertToUppercase = (strOrArray:string | string[])=>{
if(typeof strOrArray === 'string'){
return strOrArray.toUpperCase()
} else if(Array.isArray(strOrArray)){
return strOrArray.map(item=>item.toUpperCase())
}
}
}
/**
* 常用类型守卫:
* switch、字面量恒等、typeof、instanceof
* in、自定义类型守卫
*/
{
interface Dog{
wang:string
}
interface Cat{
miao:string
}
const getName = (animal:Dog | Cat) =>{
if('wang' in animal){
return animal.wang
} else if('miao' in animal){
return animal.miao
}
}
}