[TypeScript] Use the never type to avoid code with dead ends using TypeScript
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 = ; if(foo !== ) {
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.
最新文章
- React使用antd Table生成层级多选组件
- Entity Framework 6 Recipes 2nd Edition(10-7)译 ->; TPH继承模型中使用存储过程
- 谈谈我对前端组件化中“组件”的理解,顺带写个Vue与React的demo
- 让JavaScript回归函数式编程的本质
- js 中的基本类型和引用类型的区别
- 基于 fuzz 技术验证移动端 app 的健壮性
- 深入浅出设计模式——单例模式(Singleton Pattern)
- FileReader和FileWriter
- HDU5778 abs
- css中居中的居中方法
- 从Map、JSONObject取不存在键值对时的异常情况
- 第4章 简单的C程序设计——选择结构程序设计
- ACM-ICPC 2018 焦作赛区网络预赛 B Mathematical Curse(DP)
- hdu 1576 A/B 【扩展欧几里得】【逆元】
- 使用cmd命令进行导入
- 机器学习-分类器-Adaboost原理
- OC中几种延时操作的比較
- (转)FFMPEG的一些使用技巧
- [VS2008] 安装 AnkhSVN 后,选项中选择它,Pending Changes 窗口一闪而过,源代码管理工具自动跳回 【None】
- leetcode-383-Ransom Note(以空间换时间)
热门文章
- Eclipse中Git插件使用技巧:[5]还原文件
- CMake编译Makefile
- 原生js大总结三
- POJ 2284 That Nice Euler Circuit (LA 3263 HDU 1665)
- VS2012载入DLL编译出现试图载入格式不对的程序; 以及执行出现Mixed mode assembly is built against version &;#39;v2.0.50727&;#39; of the
- [D3] Basic Interactivity with D3 v4
- js进阶 12 jquery事件汇总
- (转)Nginx在RedHat中系统服务配置脚本
- vue学习笔记一:用Key管理可复用元素
- Iaas、Paas和Saas的区别