My goal is to dynamically create an array of objects, each potentially containing different keys but always following the same format as defined on myType
. However, Typescript throws an error when I attempt to do so. Below is a simplified example.
type myType = {
[key: string]: number;
};
const doesNotComplain: myType[] = [{ a: 1 }, { b: 2 }];
const doesComplain: myType[] = [1, 0, 0, 0, 1, 0].map((e) => {
if (e == 1) return { a: 1 };
return { b: 2 };
});
The error specifically occurs with doesComplain
.
Type '({ a: number; b?: undefined; } | { b: number; a?: undefined; })[]' is not assignable to type 'myType[]'.
Type '{ a: number; b?: undefined; } | { b: number; a?: undefined; }' is not assignable to type 'myType'.
Type '{ a: number; b?: undefined; }' is not assignable to type 'myType'.
Property 'b' is incompatible with index signature.
Type 'undefined' is not assignable to type 'number'.
Things I've attempted:
I have looked at solutions for similar issues, but none seem to fit my specific case.
One solution mentioned here requires a fixed amount of values in the array, which doesn't match what I need.
Other suggestions propose defining myType
with number | undefined
, but I prefer not to do this since I expect all keys to have defined values.
The only way I found to eliminate the error so far is to use // @ts-ignore
above doesComplain
, which defeats the purpose of using Typescript.