获取特定类型字段名称的类型[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

是否存在,或者有办法,能够使用这样的东西:

type X<Obj, FieldType> = ???;

interface A {
  a: number;
  b: number;
  c: string;
  d: Date;
}

type Nums = X<A, number>;    // == 'a' | 'b'
type Strings = X<A, string>; // == 'c'
type Dates = X<A, Date>;     // == 'd'

其中X是我正在寻找的通用类型(keyof Obj的子集,在本例中为keyof A)。

typescript
1个回答
1
投票

您可以使用条件类型来过滤所需类型的属性:

type X<Obj, FieldType> = {
    [P in keyof Obj]-?: Obj[P] extends FieldType ? P : never
}[keyof Obj];

interface A {
    a: number;
    b: number;
    c: string;
    d: Date;
}

type Nums = X<A, number>;    // == 'a' | 'b'
type Strings = X<A, string>; // == 'c'
type Dates = X<A, Date>;     // == 'd'

你可以查看我对这个here的解释

© www.soinside.com 2019 - 2024. All rights reserved.