类型转换是TS最好玩也是语言的灵魂,想玩好需要熟练各种手段和工具,下面一一介绍类型转换的一些常用手段。
keyof 操作
keyof 见名知其意,就是获取对象所有的key,然后返回一个新的联合类型。
例如:
复制代码
1
2
3type Point = { x: number; y: number }; type P = keyof Point;
扩展用途,将属性类型由number 修改成string:
复制代码
1
2type SPoint = {[K in P]:string}
如果一个类型由string
、number
索引签名,keyof 会返回这些类型代替。
复制代码
1
2
3
4type Arrayish = { [n: number]: unknown }; type A = keyof Arrayish; //A的类型是number
复制代码
1
2
3
4type Mapish = { [k: string]: boolean }; type M = keyof Mapish; //type M = string | number
typeof 操作
之前JS早就存在typeof,typeof可以获取对象类型
复制代码
1
2
3// Prints "string" console.log(typeof "Hello world");
TS可以根据typeof 根据上下文推断出类型:
&nsbp;
typeof对于类型不是很有用,但与其他类型运算符结合使用,可以使用typeof方便地表示许多模式。例如,让我们从查看预定义的类型ReturnType开始。它接受函数类型并生成其返回类型:
复制代码
1
2
3
4
5type Predicate = (x: unknown) => boolean; type K = ReturnType<Predicate>; //type K = boolean
如果使用ReturnType 在函数身上,会报错:
复制代码
1
2
3
4
5
6function f() { return { x: 10, y: 3 }; } type P = ReturnType<f>; //'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?
这时候可以配合typeof使用
复制代码
1
2
3
4
5
6
7
8
9
10function f() { return { x: 10, y: 3 }; } type P = ReturnType<typeof f>; //type P = { //x: number; //y: number; //}
类型检测
TS会协助检测typeof 错误
复制代码
1
2
3
4
5
6
7
8
9
10function func1(params:string) { } // Meant to use = ReturnType<typeof msgbox> let shouldContinue: typeof func1("Are you sure you want to continue?"); //',' expected.ts(1005)
最后
以上就是和谐树叶最近收集整理的关于TypeScript系列教程九《类型转换》-- keyof和typeof 操作的全部内容,更多相关TypeScript系列教程九《类型转换》--内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复