我有以下两个界面:
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
的函数,在该函数中,我确定参数name
是Api
接口的键,而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 '{}'
答案 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"];