In need of a function that accepts an optional parameter propName
, which must be a key
belonging to SOME_OBJECT
. The function should return the value of propName
if it is provided, or else return the entire OBJECT
:
Here's the code snippet:
type SOME_OBJECT = {
propA: string,
propB: number,
}
const getPropertyOrFullObject = <K extends keyof SOME_OBJECT>(propName?: K)
: SOME_OBJECT[K] | SOME_OBJECT => {
const myData: SOME_OBJECT = {
propA: "fooA",
propB: 42
};
if (propName) {
return myData[propName];
}
else {
return myData;
}
};
const propA = getPropertyOrFullObject("propA");
const propB = getPropertyOrFullObject("propB");
const fullObj = getPropertyOrFullObject();
Code can be viewed on Typescript playground
Received unexpected results instead of what was expected. Union types were returned. Check below for details:
https://i.sstatic.net/OUkvm.png