[TypeScript] Understand lookup types in TypeScript

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章

Understand images & containers

understand的安装

Utility3:Understand Dashboard Report

[Python] Understand List Comprehensions in Python

[Python] Understand Mutable vs. Immutable objects in Python

I don’t understand what you mean. 还是 I don’t understand what your means. 哪个对啊