首页 > 代码库 > [TypeScript] Understand lookup types in TypeScript
[TypeScript] Understand lookup types in TypeScript
Lookup types, introduced in TypeScript 2.1, allow us to dynamically create types based on the property keys of an object. We‘ll use the function spyOn from Jest to illustrate how lookup types can type-safe function parameters.
Considering this code:
function spyOn(obj: Object, prop: string) { console.log(obj, prop);}interface IPerson { name: string, age: number}const person: IPerson = { name: ‘John‘, age: 54};spyOn(person, ‘address‘);
We have a ‘IPerson‘ interface and we spyOn ‘person‘ object for ‘address‘ prop. IDE cannot catch any error.
If we want IDE helps to catch error, we can use generics for ‘spyOn‘ function:
function spyOn<O extends object, P extends keyof O>(obj: O, prop: P) { ....}
So what we tell TypeScript is,
- First param is an object,
- Second param is a prop of the first object
So what is ‘keyof‘?
Now TypeScript can catch the error:
[TypeScript] Understand lookup types in TypeScript
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。