Home > OS >  How to add a property on a type which is an array of objects?
How to add a property on a type which is an array of objects?

Time:03-30

I have the following type:

type MyType = {
  foo: string;
  bar: string;
}[];

How do I add a new property to this object?

E.g: add { fooBar: string } to MyType so the result is:

type MyType = {
  foo: string;
  bar: string;
  fooBar: string;
}[];

The best that I could do is this. It works, but it is quite cumbersome and I guess that something more elegant could be used

type Solution = Array<
  MyType extends Array<infer Item> ? Item & { fooBar: string } : never
>;

Thanks =)

CodePudding user response:

You can do this by getting the inner array item type by indexing the array type with number. After that, create an intersection with the new things you would like to be on the array item type. Finally, just create a new array type with that newly created item type:

type MyType = {
  foo: string;
  bar: string;
}[];

type MyBetterType = (MyType[number] & { fooBar: string; })[];
// ^? ({ foo: string; bar: string; } & { fooBar: string; })[]

TypeScript Playground Link

  • Related