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:

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; };


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

Answered By – Oblosys

Answer Checked By – Robin (AngularFixing Admin)

Leave a Reply

Your email address will not be published.