TypeScript includes a feature known as control flow analysis that is used to identify the type of a variable, based on the execution flow of a program. This feature allows TypeScript to have more precise type inference capabilities.
The following example defines a function that takes two arguments, and the type of one of them (named value) is the union type of number and array of number:
function increment( incrementBy: number, value: number | number[]) { if (Array.isArray(value)) { // value must be an array of number return value.map(value => value + incrementBy); } else { // value is a number return value + incrementBy; }}increment(2, 2); // 4increment(2, [2, 4, 6]); // [4, 6, 8]
Within the body of the function, we ...