[TypeScript] Define Custom Type Guard Functions in TypeScript
2024-09-03 10:55:17
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<T>(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.
最新文章
- MVC其实很简单(Django框架)
- C语言 回文
- 根据backup-my.cnf来生成新的事务日志文件
- 记一次PHP“Segmentation fault”调试经历
- maven为不同环境打包(hibernate)-超越昨天的自己系列(6)
- boa介绍文档
- POJ 1113 凸包模板题
- HOST1PLUS 的 VPS 主機-絕佳的性能和特惠的價格
- (Problem 13)Large sum
- Animals and Puzzle
- (中等) CF 585B Phillip and Trains,BFS。
- BOM基础(四)
- [转]Android sharedpreferences使用
- jquery初始化的三种方式
- [ZooKeeper] 1 基本概念
- elasticsearch 6.2.4添加用户密码认证
- celery使用
- WTF小程序之animation
- Dockerfile编写注意事项
- matlab 文件遍历
热门文章
- vue HTTP请求(针对vue-resource)
- c++通过管道pipe获取cmd输出的字符
- GA详解
- 博客之旅 gogogo!
- 【经验分享】IMX6开发板编译问题及解决方法
- MySQL(MMM架构使用)
- C#在sql中使用變量訪問Oracle數據庫
- AttributeError: &#39;tuple&#39; object has no attribute &#39;extend&#39;
- 计算机内存数据存储基本原理----寄存器和RAM的电路基础
- No-2.注释