简体   繁体   English

使用 Typescript 的 Pick 检索特定类型的所有键

[英]Using Typescript's Pick to retrieve all keys of a certain type

Is there a way to use Pick<T, K> to extract all keys of a certain type?有没有办法使用Pick<T, K>提取某种类型的所有键?

Example:例子:

type MyObject = {
  a: string;
  b: number;
  c: string;
  d: boolean;
}

I want to extract all string types, so final type will be:我想提取所有string类型,所以最终类型将是:

type NewType = {
  a: string;
  c: string;
}

First you'll need to extract all keys which have string value types:首先,您需要提取所有具有string值类型的键:

type StringKeys<T> = { [P in keyof T]: T[P] extends string ? P : never }[keyof T]

type NewType = Pick<MyObject, StringKeys<MyObject>>; // { a: string; c: string; }

Playground 操场

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

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