码迷,mamicode.com
首页 > 其他好文 > 详细

[TypeScript] Understand lookup types in TypeScript

时间:2017-05-24 15:52:43      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:call   create   cond   xtend   rate   script   ror   key   alt   

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

标签:call   create   cond   xtend   rate   script   ror   key   alt   

原文地址:http://www.cnblogs.com/Answer1215/p/6898881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!