2

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[];
}
2
  • 3
    Why not just string[]? An empty array is a valid string[]. You don't need to mention the zero-tuple unless you have some other use case. Commented May 28, 2019 at 16:35
  • This is actually a design flaw in the underlying TypeScript implementation, if you're curious you can read about it here but unions with multiple array types always call this error on Array.map afaik. jcalz is right, you don't need to use [] | string[], string[] is specific enough Commented May 28, 2019 at 17:23

1 Answer 1

5

[] is a tuple type, which is meant for a different kind of use case. string[] is an array type, and an empty array is still a string[] type. Your code would work without compilation errors:

type Kennel = string[]

const petDogs = (kennel: Kennel)  => {
  if (kennel.length > 0){
    return kennel.map((name:string)=>name)
  } else {
    return "no doggies to pet"
  }
}

petDogs([]);
petDogs(["Fido", "Doggo"]);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.