【问题标题】:How to make an object property depend on another one in a generic type?如何使一个对象属性依赖于泛型类型中的另一个?
【发布时间】:2022-11-30 03:24:38
【问题描述】:

我正在尝试创建一个具有依赖于另一个属性的属性的对象。

这是我迄今为止尝试过的一个非常简单的例子。
我希望从 name 推断出 Tvalue 应限制为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


【解决方案1】:

你要做什么不能用泛型来表达。

type Narrow<T extends string = string> = T;

// str type narrowing
type Out = Narrow<"hi">;
// type Out = "hi"

// default case
type Out2 = Narrow;
// type Out2 = string

// **values don't narrow the type**
let t: Narrow = "hi"
type Out3 = typeof t;
// type Out3 = string (default)

如果您要在通用字段中指定 some

const test2: TestType<"some"> = {
  name: 'some',
  value: 'thing2', // it now gives the error you're looking for.
};

但因为你不是,T 默认为 keyof TypeA,并允许你混合搭配。

您应该改为使用@jcalzunion approach。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 2020-08-21
    • 2023-03-21
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多