[TypeScript] Use the JavaScript “in” operator for automatic type inference in TypeScript

Sometimes we might want to make a function more generic by having it accept a union of different types as an argument. Using the JavaScript “in” operator, we can test for the presence of different properties on the argument object, and TypeScript will automatically infer the exact type of our object in that block. It does this by looking at all the possible types in the union and then keeping only the ones that have that specific property defined.

 

interface Admin {
  id: string;
  role: string:
}
interface User {
  email: string;
}

function redirect(usr: Admin | User) {
  if(/*user is admin*/) {
    routeToAdminPage(usr.role);
  } else {
    routeToHomePage(usr.email);
  }
}

 

So in the code above, what we can write into the if block to ensure that, it is admin type, so that IDE won't complain that, 'role' or 'email' may not be defined on user object?

 

Solution we can use is 'in' operator in Javascript:

function redirect(usr: Admin | User) {
  if("role" in usr) {
    routeToAdminPage(usr.role);
  } else {
    routeToHomePage(usr.email);
  }
}

'in' operator check whether one prop is existing on the object but also helps Typescript to narrow down the type, in this case, helps to choose from 'Admin' or 'User'.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值