I have a constant object with known keys. Each item within the object may or may not have a specific property. I need a function that, when given a key, will return the value along with its corresponding type.
My development environment is TypeScript 4.6.2.
Instead of manually typing in data.key?.property
, I require a programmatic approach for this functionality.
Here's an example scenario to illustrate what I'm looking for:
const data = {
alice: {loves: 3},
bob: {loves: 'hippos'},
charlie: {hates: 'toast'},
denise: {loves: (a:number) => `hello`}
} as const;
function personLoves(name:keyof typeof data) {
const item = data[name]
const loves = 'loves' in item ? item.loves : undefined;
// ^ this line needs improvement!
return loves;
}
const aliceLoves = personLoves('alice');
// Expecting `aliceLoves` to have type number.
const bobLoves = personLoves('bob');
// Expecting `bobLoves` to have type string or 'hippo'
const charlieLoves = personLoves('charlie');
// Expecting `charlieLoves` to be of type undefined
const deniseLoves = personLoves('denise');
// Expecting `deniseLoves` to be type (a:number) => string