38
interface IConverter {
    convert(value: number): string
}

class Converter implements IConverter {
    convert(): string { // no error?
        return '';
    }
}

const v1: IConverter = new Converter();
const v2: Converter = new Converter();

v1.convert(); // error, convert has parameter, although Converter's convert doesn't expect one
v2.convert(); // ok, convert has no parameters, although Converter implements IConverter which should has paramater

Converter implements IConverter, which has a method with one parameter, but Converter lacks this parameter. Why TS compiler doesn't raise an error if we do not fully implements this interface?

2 Answers 2

32

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Relevant FAQ entry for interested parties
7

TypeScript allows a function that takes fewer parameters to be treated as a function type that takes more parameters, because the extra parameters will just be ignored at runtime. See the handbook.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.