TypeScript interface implementing doesn't check method parameters

后端 未结 2 1549
Happy的楠姐
Happy的楠姐 2020-12-06 05:46
interface IConverter {
    convert(value: number): string
}

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


        
相关标签:
2条回答
  • 2020-12-06 05:56

    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 will 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.

    0 讨论(0)
  • 2020-12-06 05:59

    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.

    0 讨论(0)
提交回复
热议问题