码迷,mamicode.com
首页 > 其他好文 > 详细

[TypeScript] Define Custom Type Guard Functions in TypeScript

时间:2018-09-13 16:35:08      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:sid   analysis   within   esc   function   rip   nal   stat   some   

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.

[TypeScript] Define Custom Type Guard Functions in TypeScript

标签:sid   analysis   within   esc   function   rip   nal   stat   some   

原文地址:https://www.cnblogs.com/Answer1215/p/7807560.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!