[TypeScript] Define Custom Type Guard Functions in TypeScript
Posted answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.
以上是关于[TypeScript] Define Custom Type Guard Functions in TypeScript的主要内容,如果未能解决你的问题,请参考以下文章
sh spark-submit-wordcount-yarn-custom-capacity.sh
在TypeScript中放置RequireJS定义以从javascript调用