博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[TypeScript] Use the never type to avoid code with dead ends using TypeScript
阅读量:7056 次
发布时间:2019-06-28

本文共 1031 字,大约阅读时间需要 3 分钟。

Example 1: A never stop while loop return a never type.

function run(): never {   while(true){      let foo = "bar";   }}

 

Example 2: Never run If block

const foo = 123;if(foo !== 123) { let bar: never = foo;}

 

You can use this to do exhaustive checks in union types.

For example, let's say you have a variable returned from the server that can be a string or a number. You can easily add code that handles different cases using the JavaScript typeof operator. You can add an additional else, and assign the variable to a never to ensure that all types were eliminated.

declare var foo:    | string    | number;if(typeof foo === "string") {  /* todo */} else if (typeof foo === "number"){  /* todo */} else {  const check: never = foo;}

 

Later, if you need to add another type to the union, for example, a Boolean, you will now get nice errors at all the places where the new type was not handled, because only a never is assignable to a never. Now, if you go ahead and add another typeof to handle this new case, the error goes away.

转载地址:http://qgool.baihongyu.com/

你可能感兴趣的文章
Spring_Task初探(注解,XML配置)
查看>>
MyEclipse 2015优化技巧
查看>>
众推项目的最近讨论
查看>>
SD卡兼容性问题(转)
查看>>
解决ecshop登陆自动退出的莫名现象
查看>>
面试之求找两个数和为某个数、几个连续数等于某个数
查看>>
【LaTeX排版】LaTeX纸排版<两>
查看>>
C/C++函数调用方式
查看>>
Timer Swing
查看>>
Cassandra命令行CLI的基本使用
查看>>
JQuery获取浏览器窗口的可视区域高度和宽度,滚动条高度
查看>>
8、redis之事务1-redis命令
查看>>
http://www.111cn.net/jsp/Jsp-Servlet/45158.htm
查看>>
使用vlc播放器做rtsp流媒体服务器
查看>>
常用的easyui使用方法
查看>>
【C#基础】HTTP发送POST二进制数据
查看>>
rabbitmq redis
查看>>
【5集iCore3_ADP演示视频】5-3 iCore3应用开发平台摸校准
查看>>
Token原理以及应用
查看>>
iOS block分析
查看>>