2017-04-06 509 views
2

我不明白为什么下面的代码会导致错误。在这个简单的例子中,如预期的那样,Component类没有问题。但是明确定义StateBaseState延伸的通用实现似乎不通过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>' 
    } 
} 

我在这里错过了什么?

+0

它看起来像传播类型目前不支持泛型:https://github.com/Microsoft/TypeScript/issues/10727 –

+0

谢谢。我发布后我看到了。所以这个错误应该消失在2.3.1看起来像。但是另一个错误呢? – joslarson

回答

1

请注意,这不是上述问题的确切解决方案,而仅仅是一种解决方法。但是,评论太长了。

关于第二个错误,即“类型'参数{on:boolean;}'不能分配给'部分'类型'的参数,在本主题的社区已经有一些讨论。 https://github.com/Microsoft/TypeScript/issues/12793,https://github.com/DefinitelyTyped/DefinitelyTyped/pull/13155,尽管我找不到与您的场景完全匹配的任何内容。

由于某些原因,TS确实无法推断出Partial<State>Partial<BaseState>的可分配性,尽管事实上是State extends BaseState

例如,以下一段代码会导致错误。

class SampleClass<State extends BaseState> { 
    baseState: Partial<BaseState>; 

    method(state: Partial<State>): void { 
     this.baseState = state; // Type 'Partial<State>' is not assignable to type 'Partial<BaseState>'. 
    } 
} 

这对我来说显得很陌生,我会建议向TypeScript社区提交一个建议来考虑。至少他们可以解释,如果这是例外,为什么。

在上面给出的特定情况下,我建议按照以下方式明确地转换部分类型。

class GenericComponent<State extends BaseState> { 
    state: State; 

    constructor(state: State) { 
     this.state = state; 
    } 

    setState(partialState: Partial<State>) { 
     // Some logic here 
    } 

    onInput({ value }: { value: number }) { 
     this.setState({ on: value > 0 } as State); 
    } 
} 

据我看到这个代码仍然是类型安全和荣誉上State约束。

相关问题