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

Time:11-26

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

CodePudding user response:

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>
//   ^?

CodePudding user response:

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.

  • Related