Typescript: typescript doesn't check callback signatures

Created on 21 Jun 2016  路  6Comments  路  Source: microsoft/TypeScript

TypeScript Version:

1.7.5

Code

type cb = (a:number, b:number) => number;

function foo(callback: cb): void {
    callback(1,2);
}

foo(function(a, b){return 1;}); // this is OK.
foo(function(a){return 1;}); // this should fail.
foo(function(){return 1;}); // this should fail.

Expected behavior:

First call should compile. The rest shouldn't.

Actual behavior:

All calls compile cleanly.

Additional note
This is what happens, for example, with Array.prototype.sort

Question

Most helpful comment

And the fourth one does fail properly.

All 6 comments

I also had the same problem...

https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-functions-with-fewer-parameters-assignable-to-functions-that-take-more-parameters

And the fourth one does fail properly.

@kitsonk indeed, my bad. Just edited the code and removed that sample.

@RyanCavanaugh thanks Ryan. I understand that it's impossible to even use union types to define a function that takes either a 3 argument or zero argument callback like this:

type noargs = () => number;
type args<T> = (a: T, b: T, c: T) => number;
type cb<T> =  args<T> | noargs;

function sort<T>(callback: cb<T>): void {}

because sort(function(a,b){return 1}) would be a valid invocation. Right?

One way to think of it is that the invoker of the callback can only set a _maximum_ arity of the callback, not a minimum. If the callee decides it doesn't care about the 2nd argument, it's not going to be forced to declare a dummy parameter.

Was this page helpful?
0 / 5 - 0 ratings