Error when using different types of return which should have the same result
alex-vukov opened this issue Β· comments
Alex Vukov commented
π Search Terms
short circuit return error, ternary return error
π Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about short-circuit return error or ternary return error
β― Playground Link
π» Code
const config = {
primaryFunctions: {
'functionA': functionA,
'functionB': functionB,
},
secondaryFunctions: {
'functionC': functionC,
}
};
function functionA(str: string) {
return str + 'A';
}
function functionB(num: number) {
return callSecondaryFunction('functionC', true) + 'B';
}
function functionC(bool: boolean) {
const x = !!callPrimaryFunction('functionA', 'test');
// Comment this block and uncomment any of the others below:
if (x) {
return bool;
} else return false;
//return x ? bool : false;
// return x && bool
}
const callPrimaryFunction = <T extends keyof typeof config.primaryFunctions>(functionName: T, ...args: Parameters<typeof config.primaryFunctions[T]>) => {
return (config.primaryFunctions[functionName] as any)(...args);
}
const callSecondaryFunction = <T extends keyof typeof config.secondaryFunctions>(functionName: T, ...args: Parameters<typeof config.secondaryFunctions[T]>) => {
return (config.secondaryFunctions[functionName] as any)(...args);
}
console.log(callPrimaryFunction('functionA', 'test'));
console.log(callPrimaryFunction('functionB', 5));
π Actual behavior
When you go to functionC
comment the following block
if (x) {
return bool;
} else return false;
and uncomment any of the other two below:
//return x ? bool : false;
// return x && bool
you will get 'callPrimaryFunction' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.(7023)
errors everywhere even though the code should work in an identical way.
π Expected behavior
if (x) {
return bool;
} else return false;
or
return x ? bool : false;
or
return x && bool
should behave in the same way and not cause errors because they return the exact same result in Javascript.
Additional information about the issue
No response