Home > Blockchain >  How do I use different object types within an array?
How do I use different object types within an array?

Time:08-17

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.

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?

CodePudding user response:

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
  • Related