Reputation: 49
Here is my array:
const a = ['one', 'two'] as const;
Here is my object type:
type T = {
{ [key in typeof a[number]]: number;
}
Expected result:
const r: T = {
one: 0,
two: 0
}
This doesn't work:
const z: T = a.map((prop) => [prop, 0]);
It returns: Type '(number | "one" | "two")[][]' is missing the following properties from type 'T': one, two(2739)
Upvotes: 0
Views: 333
Reputation: 214
Everything looks good until that last part. That last part should be:
const z: T = a.reduce((obj, prop) => ({...obj, [prop]: 0}), {} as T);
We are reducing the 'a' array to an object, starting it out as an empty object of type T (since we know it will be populated at the end of the reduction), then the callback adds each property and sets it to 0.
Upvotes: 1