Consider the following scenario:
type Setting = {
key: "option_one",
value: number,
} | {
key: "option_two",
value: string,
}
export type SettingKey = Setting["key"];
// "option_one"|"option_two"
How can we develop a function to handle this situation?
function getSettingValue(key: SettingKey) /* : return type based on key*/ {
const setting: Setting = this.database.getSettingByKey(key);
return setting.value;
}
When trying to assign a new object with the Setting type, TypeScript correctly identifies that assigning a string value when the key is option_one
is an error.
const setting: Setting = {
key: "option_one",
value: "invalid input" // Error: Type 'string' is not assignable to type 'number'
};
Therefore, it should be possible to derive the specific data type of the value
property inside the Setting
object and utilize it as the return type for the function.
Is there a way to enforce the return type of the getSettingValue
function to be determined by the provided SettingKey
? Potentially utilizing generics rather than a generic number|string
return type.