我不明白为什么下面的代码会导致错误。在这个简单的例子中,如预期的那样,Component
类没有问题。但是明确定义State
从BaseState
延伸的通用实现似乎不通过BaseState
提供的输入信息发送,导致错误。在TypeScript中使用“extends”关键字泛型
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>) {
this.state = { ...this.state, ...partialState }; // error: Spread types may only be created from object types.
}
onInput({ value }: { value: number }) {
this.setState({ on: value > 0 }); // error: Argument of type '{ on: boolean; }' is not assignable to parameter of type 'Partial<State>'
}
}
我在这里错过了什么?
它看起来像传播类型目前不支持泛型:https://github.com/Microsoft/TypeScript/issues/10727 –
谢谢。我发布后我看到了。所以这个错误应该消失在2.3.1看起来像。但是另一个错误呢? – joslarson