博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[TypeScript] Define Custom Type Guard Functions in TypeScript
阅读量:6955 次
发布时间:2019-06-27

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

One aspect of control flow based type analysis is that the TypeScript compiler narrows the type of a variable within a type guard.

This lesson explores how you can define functions and type predicates to create your own type guards similar to the Array.isArray() method.

 

const numbers = [0, 1, 2, [3, 4], 5, [6], [7], 8, [9]];function isFlat
(array: (T | T[])[]): array is T[] { console.log(!array.some(Array.isArray)); return !array.some(Array.isArray);}if (isFlat(numbers)) { numbers;}

isFlat function return value is a boolean value. We add 'array is T[]' that adds additional information for types.

 

isFlat(numbers): numbers type is '(number|number())[]' 

but inside if statement: numbers is 'number[]', because we tell typescript, array is T[] in the return value.

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

你可能感兴趣的文章
Tip:部署sharepoint2013SP1指定SQL数据库时的小细节
查看>>
java设计模式演示样例
查看>>
MemCache分布式缓存的一个bug
查看>>
R语言屏幕输出
查看>>
创建与删除索引
查看>>
jQuery .tmpl() 用法
查看>>
HTML5新增核心工具——canvas
查看>>
myeclipse6.0下载及注冊码
查看>>
八大排序算法总结
查看>>
JBoss Jopr
查看>>
Android获取文件夹路径 /data/data/
查看>>
Robot Framework自动化测试(一)---第一个脚本
查看>>
菜鸟学SSH(十六)——Struts2内部是如何工作的
查看>>
去标签获取网页内容
查看>>
改动file header (測)
查看>>
微软职位内部推荐-Senior Speech TTS
查看>>
假如是你,你会怎么选择
查看>>
UVA - 10574 Counting Rectangles
查看>>
eclipse luna使用jdk1.8初始化
查看>>
6-11-N皇后问题-树和二叉树-第6章-《数据结构》课本源码-严蔚敏吴伟民版
查看>>