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 do I use different object types within an array?

I tried to use two different object types in an array.

There was no problem only using it as an object only.

However, the compile error shows up when used within an array.

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

Below are my example codes.

type OrType = { a: string } | { b: number };

const testObj1: OrType = { a: 'string' };  // OK
const testObj2: OrType = { b: 12 };  // OK
const testArr1: OrType[] = [testObj1, testObj2];  // OK

testArr1.map((item) => item.a);  // [ERROR] Property 'a' does not exist on type 'OrType'. Property 'a' does not exist on type '{ b: number; }'.ts(2339)
testArr1.map((item) => item.b);  // [ERROR] Property 'b' does not exist on type 'OrType'. Property 'b' does not exist on type '{ a: string; }'.ts(2339)

How do I use it?

>Solution :

You can use the in operator to check the existence of a certain key in the object and Typescript will automatically typecast the ternary result for you:

testArr1
  .map(item => 'a' in item ? item.a : undefined)
  .filter(i => i) // <--- to filter out the `undefined`s
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