• [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:

  • 相关阅读:
    HDU 1013 Digital Roots
    HDU 1290 献给杭电五十周年校庆的礼物
    几何分割问题
    HDU 1222 Wolf and Rabbit
    HDU 1997 汉诺塔VII
    HDU 1443 Joseph
    HTML的标题样式
    HDU 1568 Fibonacci
    Hope
    HDU 1071 The area
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6898881.html
Copyright © 2020-2023  润新知