我不明白为什么下面的代码会导致错误。在这个简单的示例中,Component正如预期的那样,该类没有任何问题。State但是,明确定义为从 扩展的通用实现BaseState似乎并未发送由 提供的类型信息BaseState,从而导致错误。
interface BaseState {
on: boolean;
color: string;
};
class Component {
state: BaseState;
constructor(state: BaseState) {
this.state = state;
}
setState(partialState: Partial<BaseState>) {
this.state = { ...this.state, ...partialState }; // no error
}
onInput({ value }: { value: number }) {
this.setState({ on: value > 0 }); // no error
}
}
class GenericComponent<State extends BaseState> {
state: State;
constructor(state: State) {
this.state = state;
}
setState(partialState: Partial<State>) { …Run Code Online (Sandbox Code Playgroud)