I am presenting the TypeScript code below:
type Item = {
key: number;
value: string;
items?: readonly Item[];
}
const items = [
{ key: 1, value: 'foo', items: [{ key: 3, value: 'baz' }] },
{ key: 2, value: 'bar' }
] as const;
type MyItem = typeof items[number]; // how can this be flattened?
function getItemValue<K extends MyItem['key']>(key: K): Extract<MyItem, { key: K }>['value'];
function getItemValue(key: MyItem['key']) {
return ''; // details of implementation are not necessary.
}
const x = getItemValue(1);
// ^? const x: "foo"
const y = getItemValue(2);
// ^? const x: "bar"
const z = getItemValue(3); // to make it work (it should return 'baz')
// ^?
The purpose of the getItemValue
function is to provide the value
of the item with the specified key
.
It should only allow valid keys
and return the correct corresponding value type based on the items
array.
I'm focused solely on the typings. The actual implementation of the function is irrelevant. It's working for the main items but not for the nested ones.
Is there a way to flatten the MyItem
type?
Please visit the TypeScript Playground