[TypeScript] Understand lookup types in TypeScript

本文介绍了TypeScript 2.1中引入的查找类型,并通过示例展示了如何利用这些类型确保函数参数类型的安全性。借助查找类型,开发人员可以增强代码编辑器的功能,使其能够捕捉到错误的对象属性引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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:

 

转载于:https://www.cnblogs.com/Answer1215/p/6898881.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值