After a long time reading questions and looking at the docs I still need help. My problem is quite simple. I want to define a function that returns an array when an array is given as parameter but Typescript never let me return the wanted value.
I simplified the function i want to code here as the error is still the same.
function notWorkingTernary(val: number | number[]) : typeof val extends number[] ? string[] : string{
if(Array.isArray(val)){
return val.map(v=>String(v));
}
else{
return String(val);
}
}
This function is getting the following error at the first return (line 3) :
Type 'string[]' is not assignable to type 'string'.ts(2322)
I don't understand why would Typescript want me to return a string type even when the type of val is clearly an array of number here.
If I avoid giving a return type then the return type is always string | string[] and I have to cast the return type myself each time i use the function.
What am I doing wrong here?
You want to use function signature overloading. In your case it should look like this:
function notWorkingTernary(val: number): string;
function notWorkingTernary(val: number[]): string[];
function notWorkingTernary(val: number | number[]): (string | string[]) {
if(Array.isArray(val)){
return val.map(v=>String(v));
}
else{
return String(val);
}
}
Basically, you've got one function with several "type overloads" which are handled in runtime and by declaring types you promise that runtime is compatible with typings.