简体   繁体   中英

Typescript strictNullChecks and closures

Let's say I have code like this:

function f(x: string | undefined) {
    if (x) {
        console.log(x);
        Promise.resolve()
            .then(() => g(x))  // error, x is string | undefined
    }

    // x = undefined;
}

function g(y: string) {
}

The if (x) acts as a type guard, so x has type string at the console.log . But when referenced from the closure in the .then , its type is string | undefined string | undefined . This must be because the value could change back to undefined outside the type guard, before the code in .then runs. But if it doesn't get set again, Typescript must not be doing the kind of analysis that would let it detect that.

I can work around it by using the ! operator on x . But I find that I do this sort of thing often in my codebase, and it doesn't protect against being broken later by making x undefined.

Is there any other way around this? Am I understanding the problem correctly?

I think that you can do either one of these:

(1) Use const:

function f(x: string | undefined) {
    if (x) {
        const x2 = x;
        Promise.resolve().then(() => g(x2));
    } else {
        // x = undefined;
    }
}

(2) Call g() before the promise:

function f(x: string | undefined) {
    if (x) {
        let y = g(x);
        Promise.resolve().then(() => y);
    } else {
        // x = undefined;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM