I created a data.
type PenType = {
color: string
}
type PencilType = {
darkness: string
}
const data: {
pen: PenType,
pencil: PencilType
} = {
pen: {
color: "blue",
},
pencil: {
darkness: "2B"
}
};
type DataKeys = keyof typeof data;
I now have Object data with keys and values. I did create a function to get value from the data.
type MyReturnType = PenType | PencilType;
const getMyData = (keyToGet: DataKeys): MyReturnType => {
return data[keyToGet];
}
const finalData = getMyData('pen');
console.log(finalData);
This works completely fine. But the issue is, I want to get correct type in my finalData. Since I have tried to access pen, I want return type to be PenType, not PenType | PencilType
Is there any way to achieve this?
Sandbox link: https://codesandbox.io/s/typescript-playground-export-forked-hnle7p?file=/index.ts