简体   繁体   English

获取按 object 值类型过滤的 object 键的联合类型

[英]get union type of object keys filtered by type of object value

Is there a way to get union type of object keys filtered by type of object value?有没有办法获得按 object 值类型过滤的 object 键的联合类型?

I think, type inferring in conditional type is suitable for that, so I tried below.我认为,条件类型中的类型推断适合于此,所以我在下面尝试了。 ( KeyOfValueType is what I want) KeyOfValueType是我想要的)

type Obj1 = { a: string, b: number };
type Obj2 = { c: number, d: string, e: string };

type KeyOfValueType<
    Obj extends {},
    ValueType extends Obj[keyof Obj]
> = ValueType extends Obj[infer K] ? K : never;

type Result1 = KeyOfValueType<Obj1, number>; // "b" because Obj1["b"] is equal to number
type Result2 = KeyOfValueType<Obj2, string>; // "d" | "e" because Obj2["d"] and Obj2["e"] are equals to string;

TypeScript Playground TypeScript 游乐场

But tt raises an error Type 'K' cannot be used to index type 'Obj'.但是 tt 引发错误Type 'K' cannot be used to index type 'Obj'. at Obj[infer K] .Obj[infer K]

There is the package https://github.com/piotrwitek/utility-types .有 package https://github.com/piotrwitek/utility-types It has PickByValue and PickByValueExact operators(and many other useful type operators).它具有PickByValuePickByValueExact运算符(以及许多其他有用的类型运算符)。 You can use them along with keyof to achieve your goal.您可以将它们与keyof一起使用来实现您的目标。 They indeed use conditional type and infer for that.他们确实使用条件类型并为此进行infer

type PickByValue<T, ValueType> = Pick<T, {
    [Key in keyof T]: T[Key] extends ValueType ? Key : never;
}[keyof T]>;

type R1 = keyof PickByValue<Obj1, number> //b
type R2 = keyof PickByValue<Obj2, string> //d | e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM