8

TypeScript 通过 keyof 操作符提取其属性的名称

 3 years ago
source link: https://www.joynop.com/p/413.html
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.

TypeScript 通过 keyof 操作符提取其属性的名称

TypeScript 允许我们遍历某种类型的属性,并通过 keyof 操作符提取其属性的名称。

keyof 操作符是在 TypeScript 2.1 版本引入的,该操作符可以用于获取某种类型的所有键,其返回类型是联合类型。

keyofObject.keys 略有相似,只不过 keyofinterface 的键。

const persion = {
  age: 3,
  text: 'hello world'
}

// type keys = "age" | "text"
type keys = keyof Point;
TypeScript

写一个方法获取对象里面的属性值时,一般人可能会这么写

function get1(o: object, name: string) {
  return o[name];
}

const age1 = get1(persion, 'age');
const text1 = get1(persion, 'text');
TypeScript

但是会提示报错

2636574001-8d381242574073d4.png

因为 object 里面没有事先声明的 key。

当然如果把 o: object 修改为 o: any 就不会报错了,但是获取到的值就没有类型了,也变成 any 了。

3922026489-5ce2ae62fb9c0fda.png

这时可以使用 keyof 来加强 get 函数的类型功能,有兴趣的同学可以看看 _.gettype 标记以及实现

function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
  return o[name]
}
TypeScript

1029030268-013c60b5ebfac044_articlex.png

打赏: , - (付款时请注明赞赏)

标签: typescript, keyof

添加新评论

请输入 2 + 6 = ? 的计算结果:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK