【发布时间】:2022-11-30 03:24:38
【问题描述】:
我正在尝试创建一个具有依赖于另一个属性的属性的对象。
这是我迄今为止尝试过的一个非常简单的例子。
我希望从 name 推断出 T。 value 应限制为TypeA 中的有效值。
type TypeA = {
some: 'some2';
thing: 'thing2';
};
type TypeAUnion = keyof TypeA;
type TestType<T extends TypeAUnion = TypeAUnion> = {
name: T;
value: TypeA[T];
};
const test1: TestType = {
name: 'some',
value: 'some2',
};
const test2: TestType = {
name: 'some',
value: 'thing2', // shouldn't be allowed here
};
【问题讨论】:
-
您可能想要一个联合而不是泛型类型……this approach 是否满足您的需求?如果是这样,我可以写一个答案来解释;如果没有,我错过了什么?
标签: typescript typescript-typings typescript-generics