在Typescript中扩展和使用泛型类

时间:2019-06-27 14:19:46

标签: reactjs typescript

在React Typescript项目中,我试图使用基类组件,并在State中使用额外的属性对其进行扩展。

如果我天真地将其从

更改
class ErrorBoundaryW extends PureComponent<any, State> {...}

class ErrorBoundaryW<SunState = {}> extends PureComponent<any, State & SunState> {...}

尝试分配给State时出现错误: enter image description here

我该如何实现?

我知道,除了扩展React的本机Component和PureComponent [source]之外,React在继承方面不受欢迎。但这是一种特殊情况,是一个例外,也是我唯一扩展自定义React类Component的情况。

2 个答案:

答案 0 :(得分:1)

Typescript绝不允许您将具有具体类型的对象分配给具有类型参数的对象。作为这有问题的一个示例,编译器无法检查类型参数的所有必需属性是否存在于具体类型中,因为尚未知道类型参数的最终类型。 SunState可以是{ newProp: string },因此state应该具有此属性,但是对象文字不具有此属性。

一个选择可能是使用一个抽象类并拥有一个创建子状态的抽象方法:

type State = {
    hasError: boolean
}
abstract class ErrorBoundaryW<SunState = {}> extends PureComponent<any, State & SunState> {
    constructor(props: any) {
        super(props);
        this.state = Object.assign(this.childState(), {
            hasError: true
        });
    }
    abstract childState(): SunState
}

答案 1 :(得分:0)

发生此错误是因为this.state可能是任何可能的类型–您的类中的代码无法知道SunState添加了哪些其他属性,因此无法安全地将任何值分配给{{1 }}。