我正在尝试获得这样的强类型:
enum Schema {
content = 'content',
interaction = 'interaction',
}
type ContentData = {
content: string;
};
type Data = Record<Schema, unknown> & {
[Schema.content]: ContentData;
}
type Event<T extends keyof typeof Schema> = {
event: string;
schema: T;
data: Data[T] // <----- error: Type 'T' cannot be used to index type 'Data'.
};
我现在的问题是,我想data
根据所选的架构进行输入,但 TS 会抛出错误Type 'T' cannot be used to index type 'Data'.
。
预期的行为将是:
Event<Schema.content> === {
event: string;
schema: Schema.content;
data: ContentData;
}
Event<Schema.interaction> === {
event: string;
schema: Schema.interaction;
data: unknown;
}
我怎样才能做到这一点?