Writing a function that can take an any value and returns only boolean or number in typescript, it all works fine, until we need to narrow down the return value of the function at the call site to suit some variable type(or parameter type in case of functions compositions)
Here's the function
function parseValue(value: any, defaultValue: number | boolean): number | boolean {
const valueType = typeof value;
switch (valueType) {
case 'undefined': {
return defaultValue;
}
case 'boolean': {
return value;
}
default: {
if (value == 'Unlimited')
return Infinity;
return parseInt(value);
}
}
}
The problem is seen at call site
let booleanResult = parseValue(true, true);
// Error: type boolean | number is not assignable to type boolean
let booleanCondition: boolean = booleanResult;
let numberResult = parseValue(2, 1);
// Error: type boolean | number is not assignable to type number
let numberValue: number = numberResult;
Overloading is not compatible! It looks like I can't make on overload a function with different param type(correct me if I'm wrong here)
type returnType = boolean | number;
// This overload signature is not compatible with its implementation signature
function parseValue(value: any, defaultValue: boolean): returnType;
function parseValue(value: any, defaultValue: number ): returnType{
...
}
I know we can parse the output of the function again to make it works like:
let numberValue: number = Number(numberResult);
But I'm looking for a typescript solution for this problem.
Use typescript overload the proper way:
From Typescript docs
The signature of the implementation is not visible from the outside. When writing an overloaded function, you should always have two or more signatures above the implementation of the function.
The solution was easily done writing each overload function alone, then writing the body of the function
function parseValue(value: any, defaultValue: number): number;
function parseValue(value: any, defaultValue: boolean): boolean;
function parseValue(value: any, defaultValue: number | boolean): boolean | number {
... body of function
}
My problem was solved when I've read
Again, the signature used to write the function body can’t be “seen” from the outside.