0

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)

1
  • map returns an array, not an object. You should pass the result of that map to Object.fromEntries(). Commented Jul 9, 2021 at 17:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.