Search code examples
arraystypescripttypescript-genericstypescript-utility

How can I use the classic Omit functionality applied to an array type instead of a type in typescript?


How can I use the classic Omit functionality applied to an array type instead of a type?

For example, I've the following type

type Car = {
  a: number,
  b: string,
  c: Record<string, unknown> | null
}

type Cars = Car[]

I would like to create similar types without c: Record<string, unknown> | null.

For example I could declare.

type Voiture = Omit<Car, 'c'>

type Voitures = Omit<Cars, 'c'>  // obviously not working

For code constraints, I ca't use Omit<Car, 'c'>[].

Is there a solution for this?

Thanks


Solution

  • You could use an Indexed Access Type for that to extract Car from Car[] then use Omit as usual and finally turn it back into an array.

    type Car = {
      a: number,
      b: string,
      c: Record<string, unknown> | null
    }
    
    type Cars = Car[];
    
    type Voitures = Omit<Cars[number], "c">[]
    //   ^? type Voitures = Omit<Car, "c">[] 
    

    TypeScript Playground