1

I have a custom map function in TypeScript defined as follows:

function map(arr: number[], fn: (n: number, i: number) => number): number[] {
  let returnedArray: number[] = [];
  for (let index = 0; index < arr.length; index++) {
    returnedArray.push(fn(arr[index], index));
  }
  return returnedArray;
}

This function expects the fn argument to be a function that takes two parameters: a number (n) representing the array element and a number (i) representing the index, and returns a number.

However, when I try to pass a function that only accepts one parameter, like this:

function plusone(n: number) {
  return n + 1;
}

map([1, 2, 3], plusone);

I am not getting any TypeScript errors during compilation (using tsc from the command line).

Can anyone pls tell me why?

1
  • This is an intentional, safe, and generally desirable feature of TypeScript: see the relevant FAQ entry and the answer to the questions linked above. People write things like [1, 2, 3].map(x => x+1) all the time, even though map calls the callback with more arguments. You might want to see an error, but the overwhelming majority of cases where this happens do not want an error. It's not like there's a runtime problem, is there? Commented Apr 13 at 1:58

1 Answer 1

0

Because ignoring unused parameters in callback function is a very common practice in JS, for ergonomic reason TS decides not to fight against the tide.


I always like to use an analogy when thinking about TS function type checking rules.

Imagine Alice posts a job:

I offer 10 coins, a block of wood, and a knife. Carve me a wooden cube.

That’s her expected function: takes 3 inputs, returns { shape: "cube" }.

Bob comes and says:

I only need 5 coins and the wood. I’ve got my own tools.

And he can deliver a polished cube: { shape: "cube", polished: true }

Bob (the callback function) accepts fewer inputs (ignores the knife), takes less money and he over-delivers on the result. Why shouldn’t he get the job?

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

2 Comments

This isn't parameter bivariance at all, it's not unsoundness. It's sound to do this, and it's a different, intentional feature.
@jcalz thanks for pointing out the mistake. Corrected

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.