簡體   English   中英

Typescript strictNullChecks和closures

[英]Typescript strictNullChecks and closures

假設我有這樣的代碼:

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) {
}

if (x)充當類型保護,因此xconsole.log具有類型string 但是當從.then的閉包引用時,它的類型是string | undefined string | undefined 這必須是因為在.then的代碼運行之前,值可以在類型保護之外變回未定義。 但是如果它沒有再次設置,那么Typescript就不能進行那種讓它檢測到的分析。

我可以通過使用來解決它! x運算符。 但我發現我經常在我的代碼庫中做這種事情,並且它不能防止以后通過使x undefined來破壞。

還有其他方法嗎? 我能正確理解問題嗎?

我認為你可以做其中任何一個:

(1)使用const:

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

(2)在承諾之前調用g()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM