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

40 Views Asked by At

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

2

There are 2 best solutions below

0
Behemoth On BEST ANSWER

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

0
Harrison On

So in this instance I believe you would have to do the following:

type Voitures = Omit<Cars[number], 'c'>[]

Where you are essentially doing

type Voiture = Omit<Car, 'c'>

type Voitures = Voiture[]