I have a function that can return a couple of different types and I want to specify the return using an argument:
type returnTypes = 'string' | 'object';
function getValue(returnType: returnTypes): string | Record<string, string> {
if(returnType === 'object') {
return { my: 'return value' }
}
return 'my return value';
}
interface IData {
myObjectValue: Record<string, string>;
myStringValue: string;
}
const data: IData = {
myObjectValue: getValue('object'),
myStringValue: getValue('string'),
}
The assignment to data
gets me the following errors:
Type 'string | Record<string, string>' is not assignable to type 'Record<string, string>'. Type 'string' is not assignable to type 'Record<string, string>'.
Type 'string | Record<string, string>' is not assignable to type 'string'. Type 'Record<string, string>' is not assignable to type 'string'
presumably because TypeScript thinks the return value of getValue
is wider than the types defined in my interface.
How can I instruct TypeScript based on my returnType
argument, which of the two return types I will receive?
(Or is there a more canonical way to do this, eg just separate into functions, if so what/how?
returnType
is happens only at run-time. – kshetline