打字稿泛型和类属性

时间:2018-10-06 21:56:55

标签: typescript

我目前正在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'.
        }
    }
}

TS playground link

因此,只有启用了严格的null检查,才会出现此错误。

也:

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

  • 如果我在class属性上显式设置类型,则不会出现错误。 playground

那么这是打字稿处理不好的情况还是我错过了什么/做错了什么?

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

state中重新声明Test属性时,它会基于初始化程序的类型(即{bar: undefined})获得一个新类型,如将鼠标悬停在{{1 }}。这就是为什么TypeScript认为state不能是this.state.bar之外的任何东西,即使在您检查它是真实的之后也是如此。在构造函数中初始化undefined是正确的解决方案。

相关问题