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'.

最新文章

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

热门文章

  1. 使用DRF视图集时自定义action方法
  2. Servlet中使用 Last-Modified、Expires和Cache-Control
  3. python-函数(命名空间、作用域、闭包)
  4. Android动画之仿美团加载数据等待时,小人奔跑进度动画对话框(附顺丰快递员奔跑效果)
  5. 只用120行Java代码写一个自己的区块链-4实现真正的p2p网络
  6. HDU 1495 非常可乐【BFS/倒水问题】
  7. Codeforces 1038E Maximum Matching
  8. MySQL笔记之视图的使用详解
  9. bzoj 4774: 修路
  10. new beginning