【发布时间】:2019-03-12 00:39:26
【问题描述】:
我目前正在 React 项目中使用 Typescript,并希望使用类属性来设置初始状态,但是在使用未定义的值和严格的 null 检查时遇到了一些问题。这是我的问题的最小重构,没有任何 React 特定代码来演示我的问题。
class Component<T> {
state: T;
}
interface Foo {
bar: number | undefined
}
class Test extends Component<Foo> {
state = {
bar: undefined
}
test(a: number) {
//
}
callTest() {
if (this.state.bar) {
this.test(this.state.bar) // Argument of type 'undefined' is not assignable to parameter of type 'number'.
}
}
}
所以这个错误只有在启用严格的空检查时才会出现。
还有:
如果我在构造函数中设置状态而不是通过类属性 没有错误。 playground
如果我在类属性上显式设置类型,则不会出现错误。 playground
那么这是 Typescript 处理不好还是我遗漏了什么/做错了什么?
编辑:看起来 TS-playground 不共享选项,所以请手动检查 sctrictNullChecks 以查看错误。
【问题讨论】:
标签: typescript