I have recently stepped into a piece of code similar to this
const lookup = { a: 1, b: 2, c: 3, d: 4 };
const res = ['a', 'b', 'c', 'd'].map((value) => lookup[value as keyof typeof lookup]);
I do not understand which is the point of coding this lookup[value as keyof typeof lookup] vs a simpler lookup[value].
What do I gain adding as keyof typeof lookup?
CodePudding user response:
This cast is necessary because the type of ['a', 'b', 'c', 'd'] is being inferred as string[] which is too wide to be used as the keys of lookup.
Another way of fixing this would be with a const assertion like this:
const lookup = { a: 1, b: 2, c: 3, d: 4 };
const keys = ['a', 'b', 'c', 'd'] as const;
const res = keys.map((value) => lookup[value]);
This solution is slightly better because the type is being inferred from the actual value. In your example you arbitrarily tell TypeScript that value is of type keyof typeof lookup while it may not be so it's less safe.
