TypeScript-在函数内部没有“在分配之前使用变量”

问题描述 投票:2回答:2

我想了解以下TypeScript行为:

以下代码

let a: number
if (a === undefined) {
    console.log("how?")
}

引发错误:“变量'a'在分配前已使用。”。

但是以下代码

let a: number
const f = (): void => {
    if (a === undefined) {
        console.log("how?")
    }
}
f()

工作正常,并记录“如何?”。

为什么?而且,如果a === undefined的类型为number,怎么会这样?

typescript variables initialization undefined let
2个回答
0
投票
来自Ryan Cavanaugh,是

因为我们没有内联函数的流控制效果


0
投票
if( testVariable === false)

而不是简单地

if( !testVariable )
© www.soinside.com 2019 - 2024. All rights reserved.