[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'.
最新文章
- jquery插件开发
- JS 数组去重复值
- Altium Designer 多个输出相连等问题报错解决方法
- SAM4E单片机之旅——20、DMAC之使用Multi-buffer进行内存拷贝
- 常用tcode
- JavaScript DOM动态创建(声明)Object元素
- 《Java数据结构与算法》笔记-CH4-2用栈实现字符串反转
- Navicat_Preminum
- 第7章 桥接模式(Bridge Pattern)
- PQ分区魔术师v9.0 中文版
- CentOS 安装 clamav
- 【ASP.NET Core】准备工作:在 Windows 10 上配置 Linux 子系统
- CentOS7上安装Nginx、PHP、MySQL
- 从一个git仓库拷贝到另一个git仓库
- Vue-Router路由Vue-CLI脚手架和模块化开发 之 vue-router路由
- mybatis笔记02
- Python——WeRobot(微信公众号开发)
- 团队第一次 # scrum meeting
- Ubuntu解压zip包中文乱码
- centos 7下ldap安装