RJM
RJM

Reputation: 1178

Typescript not checking function argument types declared by interfaces

I was expecting TWO errors when compiling the code below, but typescript compiles it without any errors.

interface IFoo{
    Bar(callback: (arg:string) => void):void;
}

class Foo implements IFoo {
    public Bar(callback: () => void):void{
        callback();
    }
}

var foo: IFoo;
foo = new Foo();
foo.Bar(() => {
    console.log("Hi");
})

Expected Error 1: IFoo.Bar requires a function argument which itself takes a string argument. However, when Foo implements IFoo, Foo.Bar is declared to take a function argument with NO arguments. I would expect this to be a type error.

Expected Error 2: foo is of type IFoo. foo.Bar is called with a function argument that takes no arguments, contrary to the definition of Bar in IFoo. I would expect this to be a type error.

So both when declaring a concrete implementation of an interface method, and also when calling the interface method, it seems that the type of the function signature is not being enforced.

Clearly I am misunderstanding how typescript handles type checking of function arguments declared by an interface. Can someone explain why this compiles without error?

Upvotes: 8

Views: 2852

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 220884

This is answered in the TypeScript FAQ. Here is the text of that answer:

This is the expected and desired behavior. First, refer to the "substitutability" primer at the top of the FAQ -- handler is a valid argument for callback because it can safely ignored extra parameters.

Second, let's consider another case:

let items = [1, 2, 3];
items.forEach(arg => console.log(arg));

This is isomorphic to the example that "wanted" an error. At runtime, forEach invokes the given callback with three arguments (value, index, array), but most of the time the callback only uses one or two of the arguments. This is a very common JavaScript pattern and it would be burdensome to have to explicitly declare unused parameters.

Upvotes: 6

Related Questions