[TypeScript] Define Custom Type Guard Functions in TypeScript

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.

posted @ 2018-09-13 14:50  Zhentiw  阅读(426)  评论(0编辑  收藏  举报