3
一文读懂TS in操作符
source link: https://www.fly63.com/article/detial/11553
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
更新日期: 2022-05-23阅读量: 10标签: 操作符分享
扫一扫分享
in操作符作用: 遍历类型
type roles = "tester" | "developer" | "manager";
const staffCount: { [k in roles]: number } = {
tester: 100,
developer: 200,
manager: 300,
};
上述代码规定 staffCount 是一个对象,属性名为 roles 约束的三个,值为 number 类型
- 类型变量 k,以此绑定到对象的每一个属性
- 遍历三个字符串字面量组成的联合类型 roles
- number 为每个属性的值的类型
在映射类型里,新类型以新的规则转换基类型的每一条规则.类似于class的继承
interface publicObj {
// 定义一个开放的对象
name: string;
age: number;
}
type ReadonlyObj<T> = { // 需要传递一个类型参数
readonly [K in keyof T]: T[K]; // keyof T 返回联合类型 in 再遍历该联合类型
};
// 使用
let obj: ReadonlyObj<publicObj> = {
name: "myName",
age: 6,
};
obj.name = "yourName"; // 无法分配到 "name" ,因为它是只读属性。ts(2540)
TIPS:T[k]表示值为 T 的每一个属性的类型 类似于 JS 中for (const key in obj) {obj[key];}中的 obj[key]
作者:Yune_Neko
来源:https://www.cnblogs.com/UmaruChan/archive/2022/05/20/16291726.html
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK