【发布时间】:2020-07-27 03:54:25
【问题描述】:
我不明白为什么下面的代码会导致错误。在这个简单的示例中,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>) {
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>'
}
}
我在这里错过了什么?
【问题讨论】:
-
目前泛型似乎不支持传播类型:github.com/Microsoft/TypeScript/issues/10727
-
谢谢。我发帖后就看到了。所以这个错误应该随着 2.3.1 的样子消失。但是另一个错误呢?
标签: generics typescript