小编jos*_*son的帖子

在 TypeScript 泛型中使用“extends”关键字

我不明白为什么下面的代码会导致错误。在这个简单的示例中,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)

generics typescript

5
推荐指数
1
解决办法
2730
查看次数

标签 统计

generics ×1

typescript ×1