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?
A TypeScript Interface can include method declarations using arrow functions or normal functions, it can also include properties and return types. The methods can have parameters or remain parameterless.
An interface type cannot be passed as a parameter. When running TypeScript code, you are really compiling it down to JavaScript and then running the JavaScript. An interface is a TypeScript compile-time construct, so at runtime, there is no such thing as an interface type to call functions on or inspect properties of.
In TypeScript, a class can implement interfaces to enforce particular contracts (similar to languages like Java and C#).
What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With