【发布时间】:2021-07-18 07:05:01
【问题描述】:
我正在尝试编写一个泛型类型,它采用根级属性名称并返回嵌套在它下面的属性的联合类型。例如:
interface operations {
updateSomething: {
"201": {
schema: number;
};
"400": {
schema: string;
};
};
}
如果我想获得updateSomething 类型的“模式”,它应该解析为number | string。非通用版本工作正常:
type UpdateSomethingSchema =
operations["updateSomething"][keyof operations["updateSomething"]]["schema"];
// string | number ✓
我编写泛型类型的尝试是:
type SchemaOf<
O extends keyof operations
> = operations[O][keyof operations[O]]["schema"];
但这给了我一个错误:
Type '"schema"' cannot be used to index type 'operations[O][keyof operations[O]]'.ts(2536)
有趣的是,如果我忽略该错误,该类型似乎确实有效:
type UpdateSomethingSchema = SchemaOf<"updateSomething">;
// string | number ✓
是我做错了什么,还是 TypeScript 的限制?
【问题讨论】:
标签: typescript typescript-generics