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 add a property on a type which is an array of objects?

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:

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 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 =)

>Solution :

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

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