Skip to content
Advertisement

Why TypeScript doesn’t produce an error for a function implementation that doesn’t match interface

Say I have the following code:

interface Fn {
  (number, string): string;
}

const f: Fn = (v1, v2) => v1;

f(1, 2);

I expected TS to emit an error, because if v1 is number and the implementation of the function returns that v1, then it means that the function f returns number type, while the interface says it should return a string. But TS doesn’t complain. What am I missing here?

Advertisement

Answer

Your interface declaration is incorrect. It should have a variable name and its type. In your case number, string are being treated as variables of type any

interface Fn {
    (v1: number, v2: string): string;
}

const f: Fn = (v1, v2) => v1;

f(1, 1);

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement