I have an array that holds object with constant properties. I wish to use those properties to access data from another objects, like so:
const someObject = {
mean: { a: 100, b: 200 },
median: { c: 300, d: 400 },
} as const;
const someArray = [
{ type: 'mean', units: 'a' },
{ type: 'mean', units: 'b' },
{ type: 'median', units: 'd' },
] as const;
type ArrayItem = (typeof someArray)[number];
function accessItem({ type, units }: ArrayItem) {
const group = someObject[type];
const value = group[units];
return value;
}
const resultArray = someArray.map(accessItem);
Now, ArrayItem is a union of three types. Unfortunately, on the deconstruction, typescript doesn’t understand that there are only certain allowed value pairs of type/units, and so units
becomes a type 'a' | 'b' | 'd'
. Now, what would be an idiomatic way of telling TypeScript that if type === 'mean'
then units
is of type 'a'| 'b'
and it should be safe to use it for indexing the group object?
Playground link: https://tsplay.dev/WoeVjN