TypeScript interface implementing doesn’t check method parameters

Typescript uses structural typing to determine type compatibility. For functions this means that you don’t need to have the exact same signature for the declaration and the implementation, as long as the compiler can determine the implementation to be safe to call through the declaration.

In this case this boils down to, a function with less parameters can be an implementation for a function declaration with more parameters as the extra passed in parameters will be ignored by the implementation, so no runtime error can occur because of this (for the most cases anyway, there might be corner cases on things that depend on Function.length)

The reason you get an error on v1 but not v2 is because once the assignment is done the compiler only knows the type of the variable not what you originally assigned into it and will check based on the actual type of the variable. So for v1 this means IConverter.convert requires a parameter, no way to know it does not. For v2 it will check Converter.convert which is known to require no arguments.

Leave a Comment