取决于类型,解构失败

时间:2019-06-20 18:57:35

标签: typescript typescript-typings

我有以下两个界面:

export interface Converter<T> {
  decode?: Decoder<T>;
  encode?: Encoder<T>;
  notify?: Notifier<T>;
  type?: T;
}

export interface Api {
  state: Converter<State>;
  water: Converter<Water>;
  version: Converter<Versions>;
}

在此类中,我使用这些接口。特别是,我有一个名为write的函数,在该函数中,我确定参数nameApi接口的键,而value是对应的Generic

export default class Characteristic {
  private api: Api;

  public async write<Name extends keyof Api, Value = Api[Name]["type"]>(
    name: Name,
    value: Value
  ): Promise<void> {
    const { encode } = this.api[name];
    const buffer = encode(value);
    //                    ^^^^^
  }
}

此模式可以按预期工作,但是在这里,我对value收到了一个我不太了解的错误:

Type '"sleep" | "goingToSleep" | "idle" | "busy" | "espresso" | "steam" | "hotWater" | "shortCal" | "selfTest" | "longCal" | "descale" | "fatalError" | "init" | "noRequest" | "skipToNext" | ... 7 more ... | Versions' is not assignable to type 'Value'.
  '"sleep" | "goingToSleep" | "idle" | "busy" | "espresso" | "steam" | "hotWater" | "shortCal" | "selfTest" | "longCal" | "descale" | "fatalError" | "init" | "noRequest" | "skipToNext" | ... 7 more ... | Versions' is assignable to the constraint of type 'Value', but 'Value' could be instantiated with a different subtype of constraint '{}'.
    Type '"sleep"' is not assignable to type 'Value'.
      '"sleep"' is assignable to the constraint of type 'Value', but 'Value' could be instantiated with a different subtype of constraint '{}'

1 个答案:

答案 0 :(得分:0)

我认为Typescript在这里抱怨Value缺少约束。您为其指定了默认值,但仍可以将其覆盖为其他类型。

您是否需要将Value类型设为泛型?您可以这样更改方法签名:

public async write<Name extends keyof Api>(
  name: Name,
  value: Api[Name]["type"]
): Promise<void> {

(可选)添加类型助手以使其看起来更整洁:

type ValueFor<Name extends keyof Api> = Api[Name]["type"];