打字稿不会在构造函数之外捕获“状态”类型错误?
Typescript doesn't catch `state` type errors outside of constructor?
在上图中,我错误地设置了默认 state
值(this_is_not_ok
不是 State
接口的一部分)。不过,Typescript 似乎并不介意。解决此问题的一种方法是显式添加类型注释。
我也可以使用 constructor()
:
来解决这个问题
constructor(){
super();
this.state = {spelling_error: "wrong"};
}
为什么类型推断在第一个示例中不起作用?
I have set default state values incorrectly
你没有设置错误的值。您只是简单地编写了一个 class,它比基础 class 具有更多的状态,这本身并不是一个错误 。当你写一个派生 class 时,你可以拥有比你的基础 class.
更多的东西
当您编写 class 属性 初始化程序而不使用类型注释时,TypeScript 会根据初始化程序推断 属性 的类型:
interface Bar {
stuff: { x: number }
}
class Foo implements Bar {
stuff = {
x: 10, y: 3
}
}
const f = new Foo();
console.log(f.stuff.y); // OK: f.stuff is of type { x: number; y: number; }
implements
检查仅表示 "Make sure this class can be used as the interface type"。同样的事情发生在派生 class 上:因为你有 至少 基础合约规定的东西 class,那么一切都很好。
如果您有显式类型注释,或在构造函数中进行初始化,则适用分配对象文字的一般规则 - 不允许额外的属性。
尽管如此,此行为可能会在 TypeScript 的未来版本中发生变化。参见 https://github.com/Microsoft/TypeScript/issues/10570
在上图中,我错误地设置了默认 state
值(this_is_not_ok
不是 State
接口的一部分)。不过,Typescript 似乎并不介意。解决此问题的一种方法是显式添加类型注释。
我也可以使用 constructor()
:
constructor(){
super();
this.state = {spelling_error: "wrong"};
}
为什么类型推断在第一个示例中不起作用?
I have set default state values incorrectly
你没有设置错误的值。您只是简单地编写了一个 class,它比基础 class 具有更多的状态,这本身并不是一个错误 。当你写一个派生 class 时,你可以拥有比你的基础 class.
更多的东西当您编写 class 属性 初始化程序而不使用类型注释时,TypeScript 会根据初始化程序推断 属性 的类型:
interface Bar {
stuff: { x: number }
}
class Foo implements Bar {
stuff = {
x: 10, y: 3
}
}
const f = new Foo();
console.log(f.stuff.y); // OK: f.stuff is of type { x: number; y: number; }
implements
检查仅表示 "Make sure this class can be used as the interface type"。同样的事情发生在派生 class 上:因为你有 至少 基础合约规定的东西 class,那么一切都很好。
如果您有显式类型注释,或在构造函数中进行初始化,则适用分配对象文字的一般规则 - 不允许额外的属性。
尽管如此,此行为可能会在 TypeScript 的未来版本中发生变化。参见 https://github.com/Microsoft/TypeScript/issues/10570