I want to loop through an array of objects in js to find the element with a specific key.
It's worth noting that, the 'specific key' will exist in only one of the objects and no more. (it is also possible the 'key' will not exist in any of the objects)
For Example:
const arr: [
{ foo: number; fooo: number },
{ bar: number; barr: number },
{ baz: number; bazz: number }
] = [
{ foo: 100, fooo: 1 },
{ bar: 3, barr: 200 },
{ baz: 0, bazz: 0 },
];
I am using below code to find the object which has the wanted key:
const wantedObj = arr.find((el) => (typeof el.baz !== 'undefined'))
Since it is possible for the key to have a falsey value (ex: 0 ), I am checking (typeof el.baz !== 'undefined') condition.
But I get the TS error of
Property 'bazz' does not exist on type '{ foo: number; fooo: number; } | { bar: number; barr: number; } | { baz: number; bazz: number; }'.
Property 'bazz' does not exist on type '{ foo: number; fooo: number; }'.ts(2339)
Why is TS giving this error while I have obviously defined the type of arr? and how to fix it?
bazzdoes not exist on{ foo: number; fooo: number; }. Elements inarrcould be of type{ foo: number; fooo: number; }. One way to handle that would be to use type guards. Also see narrowing