我正在尝试使用TypeScript定义一个状态机,并在类型级提供一些检查。
为此,我不仅需要保持值级别的配置,还需要保持类型级别的配置,以便能够引发编译时错误,如“您不能从最终状态转换”或“目标状态不存在”等。
让我们从状态"type“定义开始。状态节点可以是“初始”、“状态”或“最终”类型。
因此,在我的配置中,我将保留一个带有type的属性,即类型的文字值。(例如,参见EmptyStateConfig类型)。
为了更新类型,我需要在类型级别上做的是覆盖字段的类型,并用一个新的类型替换它。
调用new State().type("final")应该以State<{ type: "final" }>类型返回。
不幸的是,TS对我大喊大叫,说类型方法的返回类型是无效的,因为它不满足AnyStateConfig类型,因为它缺少覆盖的未接触键(但它们就在那里!)
请查看以下代码以了解更多信息:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type Override<T, K extends keyof T, V> = Omit<T, K> & { [N in K]: V }
type AnyStateConfig = {
type: "initial" | "state" | "final"
states: {[K: string]: AnyStateConfig}
}
type EmptyStateConfig = {
type: "state"
states: {}
}
class State<C extends AnyStateConfig = EmptyStateConfig>{
constructor(
public readonly config: C
){
}
// the following line breaks.
type<StateType extends AnyStateConfig["type"]>(type: StateType): State<Override<C, "type", StateType>>{
return new State({ ...(this.config as any), type})
}
}将TS 2.9或3.0与strict配合使用: true
发布于 2018-08-01 02:36:57
TypeScript不够聪明,无法推断如果是C extends AnyStateConfig,那么Exclude<keyof C, "type">必须包含"states"。看起来an existing issue report来了。我发现的一个解决方法是再次将C与AnyStateConfig相交:
type<StateType extends AnyStateConfig["type"]>(type: StateType): State<Override<AnyStateConfig & C, "type", StateType>>{
return new State({ ...(this.config as any), type})
}https://stackoverflow.com/questions/51619790
复制相似问题