类型缩小:type Narrowing
类型守卫是 一个值确保在该类型的范围内。
1. in 关键字
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16interface InObj1 { a: number, x: string } interface InObj2 { a: number, y: string } function isIn(arg: InObj1 | InObj2) { // x 在 arg 打印 x if ('x' in arg) console.log('x') // y 在 arg 打印 y if ('y' in arg) console.log('y') } isIn({a:1, x:'xxx'}); isIn({a:1, y:'yyy'});
2. typeof 关键字
复制代码
1
2
3
4
5function isTypeof( val: string | number) { if (typeof val === "number") return 'number' if (typeof val === "string") return 'string' return '啥也不是' }
typeof 只支持:typeof 'x' === 'typeName' 和 typeof 'x' !== 'typeName',x 必须是 'number', 'string', 'boolean', 'symbol'。
3. instanceof
复制代码
1
2
3
4
5
6
7
8function creatDate(date: Date | string){ console.log(date) if(date instanceof Date){ date.getDate() }else { return new Date(date) } }
4. 自定义类型保护和类型谓词
复制代码
1
2
3
4
5
6function isNumber(num: any): num is number { return typeof num === 'number'; } function isString(str: any): str is string{ return typeof str=== 'string'; }
最后
以上就是热情百褶裙最近收集整理的关于『TypeScript』类型守卫的全部内容,更多相关『TypeScript』类型守卫内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复