是否可以在下面的示例中隐含地说明name
属性的可能选项(基于key
):
type TypeMap = {
A: 1 | 2 | 3;
B: 4 | 5 | 6;
};
type InnerType<TKey extends keyof TypeMap> = {
key: TKey;
name: TypeMap[TKey];
// + other properties;
};
type OuterType = {
x: InnerType; // Should be agnostic at this point
y: InnerType; // but typescript requires a generic definition
};
const foo: OuterType = {
x: { key: "A", name: 2 },
y: { key: "B", name: 4 },
};
我能想到的最接近的结果如下所示(但我宁愿不必更改各自类型的格式):
type TypeMap = {
A: 1 | 2 | 3;
B: 4 | 5 | 6;
};
type InnerType = {
data: Partial<{ [key in keyof TypeMap]: TypeMap[key] }>;
// + other properties
};
type OuterType = {
x: InnerType;
y: InnerType;
};
const foo: OuterType = {
x: { data: { A: 2 } }, // not blocking me from using `{}` or `{ A: 2, B: 4 }` on the same object
y: { data: { B: 4 } },
};
另一种方法如下(但不基于键进行限制):
type TypeMap = {
A: 1 | 2 | 3;
B: 4 | 5 | 6;
};
type InnerType = {
key: keyof TypeMap;
name: TypeMap[keyof TypeMap];
// + other properties;
};
type OuterType = {
x: InnerType;
y: InnerType;
};
const foo: OuterType = {
x: { key: "A", name: 2 }, // allows me to use `{ key: "A", name 4 }`
y: { key: "B", name: 4 },
};