1. 程式人生 > >[TypeScript] Define Custom Type Guard Functions in TypeScript

[TypeScript] Define Custom Type Guard Functions in TypeScript

nal ria console tro res one inf arr asp

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