Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get only arrays or another type from interface?

I have an interface like that:

interface Car {
  model: string;
  owners: string[];
}

And I want to get only array properties:

type NewCar = OnlyArrays<Car>

And this will be equal to:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

type NewCar = {
  owners: string[];
}

Type it’s not important, array just for example.

I’ve tried this code but it doesn’t work:

function getCar<T = Car>(id: string): { [P in keyof T]: T[P] extends array ? string[] : string; };

>Solution :

You can declare a mapped type and remap the keys (docs) to include only those keys for which the value extends an array:

type OnlyArrays<T> = {
  [K in keyof T as T[K] extends Array<infer _> ? K : never]: T[K]
}

type NewCar = OnlyArrays<Car>
// type NewCar = { owners: string[] }

TypeScript playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading