gpt4 book ai didi

javascript - 流(类型)不尊重我对类属性所做的手动检查

转载 作者:行者123 更新时间:2023-12-01 02:22:34 25 4
gpt4 key购买 nike

一个例子:

class MyClass {
foo: ?string;
constructor(foo) {
this.foo = foo;
}

doSomething() {
if (!this.foo) throw new Error();
console.log('hi'); // if I comment this line, I get no errors!
const myFoo: string = this.foo;
}
}

我收到以下错误:

12: const myFoo: string = this.foo; ^ Cannot assign this.foo to myFoo because null or undefined 1 is incompatible with string [2].

您可以现场观看here .

如您所见,我确实确保设置了 this.foo。但是,如果检查后执行了任何代码,尽管该代码没有执行任何操作,但它会忽略我的检查。

最佳答案

Flow 不允许这样做,因为就其而言,console.log() 调用可能会更改 this.foo 的值,这是正确的。 Flow 理论上可以是特殊情况 console.log 因为它不会有副作用,但它实际上可以是任何函数调用。如果您希望它起作用,您需要首先获取该值,例如

doSomething() {
const foo = this.foo;
if (!foo) throw new Error();
console.log('hi');
const myFoo: string = foo;
}

doSomething() {
if (!foo) throw new Error();
const foo = this.foo;
console.log('hi');
const myFoo: string = foo;
}

因为 foo 变量的类型无法更改,因为它没有在任何地方重新分配。

关于javascript - 流(类型)不尊重我对类属性所做的手动检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49097551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com