我是靠谱客的博主 热情百褶裙,这篇文章主要介绍『TypeScript』类型守卫,现在分享给大家,希望可以做个参考。

类型缩小:type Narrowing

类型守卫是 一个值确保在该类型的范围内。

1. in 关键字

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface 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
5
function 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
8
function creatDate(date: Date | string){     console.log(date)     if(date instanceof Date){         date.getDate()     }else {         return new Date(date)     } }

4. 自定义类型保护和类型谓词

复制代码
1
2
3
4
5
6
function isNumber(num: any): num is number { return typeof num === 'number'; } function isString(str: any): str is string{ return typeof str=== 'string'; }

最后

以上就是热情百褶裙最近收集整理的关于『TypeScript』类型守卫的全部内容,更多相关『TypeScript』类型守卫内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(57)

评论列表共有 0 条评论

立即
投稿
返回
顶部