TypeScript Interface Function Property: What’s the difference?

1.) There is a difference between method and function property declaration:

interface InterfaceA {
  doSomething(data: object): boolean; // method declaration
}

interface InterfaceB {
  doSomething: (data: object) => boolean; // function as property declaration
}

2.) TypeScript 2.6 introduces a compiler flag for stronger-typed, sound function types:

Under --strictFunctionTypes function type parameter positions are checked contravariantly instead of bivariantly. The stricter checking applies to all function types, except those originating in method or constructor declarations. (my emphasis)

So in general that is a good thing. In your example, InterfaceB has following contract: “Every function that can deal with a general object is compatible”. But you want to assign a function doIt, that expects specific objects of type { type: string; } as input. A client that uses InterfaceB thinks, it is enough to pass object, but the implementation doIt wants something more concrete, so you rightfully get that error.

And why doesn’t the error happen with InterfaceA ?

In contrast, methods like doIt in InterfaceA are excluded from --strictFunctionTypes for practical reasons. The developers decided the type system to be not too pendantic with built-in methods of Array etc. to have a reasonable balance between correctness and productivity.

So, in favor of stronger types, I would prefer the following type, which works for your case (sample):

interface InterfaceB {
  doSomething: ((data: { type: string; }) => boolean) | RegExp;
}

Leave a Comment