Why do TypeScript functions work differently in the parent area?

I have this code:

function isNumberArray(l: any[]): l is number[] {
    let res = true;
    for (let e of l) {
        res = res && (typeof e === 'number');
    }
    return res;
}
let arr:(number|string)[] = [1, 2];
if (isNumberArray(arr)) {
    let res1: number = arr[1]; //OK
    let res2: number = [1].map(i => arr[i])[0]; // ERROR: Type 'string | number' is not assignable to type 'number'
}

For some reason, the variable arr has different types in two lines inside the if block. Why?

+4
source share
1 answer

Great question. The main reason here is that TypeScript does not know that the callback is called immediately and thus makes a conservative assumption that the function can be called later after other assignments could happen.

Consider the following code:

let x: string | number = "hello world";
foo(() => console.log(x.substr(2)));
x = 42;

? . , foo (, foo is window.setTimeout). !

, const let, TypeScript , "":

const arr:(number|string)[] = [1, 2];
if (isNumberArray(arr)) {
    let res1: number = arr[1]; //OK
    let res2: number = [1].map(i => arr[i])[0]; // OK
}
+2

Source: https://habr.com/ru/post/1655839/


All Articles