简体   繁体   中英

Typescript Utility type to extract properties from an interface having a specified type

I would want to generate a new object type having only the properties of another Object that matches the requested types. Like Pick do, but specifying the types and not the property names.

For example:

interface A {
  a: string;
  b: number;
  c: string[];
  d: { [key: string]: never };
}
interface B extends PickPropertyTypes<A, string | number>{}

The interface B should have only the properties a: string and b: number resulting in an interface like

{
  a: string;
  b: number;
}

Is it possible?

Thanks

interface A {
  a: string;
  b: number;
  c: string[];
  d: { [key: string]: never };
}

type PickPropertyTypes<T, V> = {
  [K in keyof T as T[K] extends V ? K : never] : T[K]
}

type B = PickPropertyTypes<A, string | number>
//   ^?

Another solution than the one already presented is to first introduce a helper type that extract keys of given type but only keys that match the criteria.

Only then helper type is used to create the actual structural type.

interface A {
  a: string;
  b: number;
  c: string[];
  d: { [key: string]: never };
}

type ExtractPropertyTypes<T, U> = { [K in keyof T]: T[K] extends U ? K : never; }[keyof T]
type PickPropertyTypes<T, V> = { [K in ExtractPropertyTypes<T, V>]: T[K] }

type Test = PickPropertyTypes<A, string | number>

This approach mimics the way Pick it build on Extract and Omit on Exclude .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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