Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript泛型和类属性_Typescript - Fatal编程技术网

Typescript泛型和类属性

Typescript泛型和类属性,typescript,Typescript,我目前正在React项目中使用Typescript,希望使用类属性来设置初始状态,但在使用未定义的值和严格的空检查时遇到了一些问题。这里是我的问题的最小重构,没有任何特定于React的代码来演示我的问题 class Component<T> { state: T; } interface Foo { bar: number | undefined } class Test extends Component<Foo> { state = {

我目前正在React项目中使用Typescript,希望使用类属性来设置初始状态,但在使用未定义的值和严格的空检查时遇到了一些问题。这里是我的问题的最小重构,没有任何特定于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'.
        }
    }
}
类组件{
国家:T;
}
接口Foo{
条形图:编号|未定义
}
类测试扩展了组件{
状态={
酒吧:未定义
}
测试(a:编号){
//
}
callTest(){
if(this.state.bar){
this.test(this.state.bar)//类型为“undefined”的参数不能分配给类型为“number”的参数。
}
}
}

因此,只有启用严格的空检查时,才会出现此错误

此外:

  • 如果我在构造函数中设置状态而不是通过类属性 没有错误

  • 如果在class属性上显式设置type,则不会出现错误

那么这是一个Typescript处理不好的案例,还是我遗漏了什么/做错了什么


编辑:因此TS游乐场似乎不共享选项,因此请手动检查sctrictNullChecks以查看错误。

因为未定义的
在Typescript中被视为独立类型。您正在将一个
未定义的
传递给测试函数类型为
number
的参数。如果确定测试函数可以接受
未定义的
,只需允许
未定义的
作为可接受的参数类型:

test(a: number | undefined) {
        //
}

当您在
Test
中重新声明
state
属性时,它会根据初始值设定项的类型获得一个新类型,即
{bar:undefined}
,您可以通过将鼠标悬停在
state
上看到。这就是为什么TypeScript认为
This.state.bar
不能是除
undefined
之外的任何东西,即使在您检查它是否真实之后也是如此。在构造函数中初始化
状态
是正确的解决方案。

Hmmm,很抱歉,我不想这样做。首先,这并不能解释如果我在构造函数中初始化状态,代码为什么会工作。第二个
test
可能是一个我不影响的外部函数。@giggo1604在这种情况下,你能分享你的构造函数吗?如果
test
是一个外部函数,我认为一个选项是在将参数传递给
test
之前进行空检查。更新了原始帖子,请注意编辑评论。谢谢你的帮助