I have a function whose parameter can either be an empty array or an array with strings.
So I handle this with a union type of [] | string[]
Then, Inside the function, I check to see if the array.length > 0, and if it IS, then I map over the parameter.
type Kennel = [] | string[]
const petDogs = (kennel: Kennel) => {
if (kennel.length > 0){
return kennel.map((name:string)=>name)
} else {
return "no doggies to pet"
}
}
However, on compilation, I get the error
Cannot invoke an expression whose type lacks a call signature. Type '(<U>(callbackfn: (value: never, index: number, array: never[]) => U, thisArg?: any) => U[]) | (<U>(callbackfn: (value: string, index: number, array: string[]) => U, thisArg?: any) => U[])' has no compatible call signatures
I have tried using function overloading, but it didn't solve the compilation error.
example:
interface PetDogs {
(kennel: []): string;
(kennel: string[]): string[];
}
string[]? An empty array is a validstring[]. You don't need to mention the zero-tuple unless you have some other use case.Array.mapafaik. jcalz is right, you don't need to use[] | string[],string[]is specific enough