在一个React Typescript项目中,我尝试使用一个基类组件,并在State中使用一个额外的属性来扩展它。
如果我天真地将它从
class ErrorBoundaryW extends PureComponent<any, State> {...}
至
class ErrorBoundaryW<SunState = {}> extends PureComponent<any, State & SunState> {...}
尝试分配给State时出现错误:
我如何才能做到这一点?
我知道除了扩展React的原生组件和PureComponent [source]之外,在React中使用继承也是不受欢迎的。但这是一个特例,是一个异常,也是我唯一一次扩展自定义React类组件。
发布于 2019-06-27 14:31:14
Typescript永远不会允许您将具有具体类型的对象分配给具有类型参数的对象。例如,编译器无法检查类型参数的所有必需属性是否都存在于具体类型中,因为类型参数的最终类型尚不清楚。SunState
可以为{ newProp: string }
,因此state
应该具有此属性,但object文本却没有此属性。
一种选择是使用抽象类,并具有创建子状态的抽象方法:
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
}
发布于 2019-06-27 14:27:17
出现此错误是因为this.state
可能是任何可能的类型-您的类中的代码无法知道SunState
添加了哪些附加属性,因此它无法安全地将任何值赋给this.state
。
https://stackoverflow.com/questions/56793109
复制相似问题