Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS Interface doesn't force functions signature on implementers

interface test{
    foo(boo:string);
}
class coo implements test{
    foo(){

    }
}

In playGround this doesn't generate and error although the function signature is not as the interface says, the expected behavior of interface is to force the signature..

why is this behavior?

Thanks

like image 244
Bashar Ali Labadi Avatar asked Oct 31 '12 08:10

Bashar Ali Labadi


2 Answers

This is interesting. The TypeScript team are quite clever chaps and they decided to do this deliberately.

The idea is that if your function can operate correctly without being passed an argument, it can safely ignore the argument and satisfy the interface. This means you can substitute your implementation without having to update all of the calling code.

The interface ensures that the argument is passed in all cases where you are consuming the interface - so you get type checking on the callers and it actually doesn't matter that your concrete class doesn't need any parameters.

Interface Function Parameter Not Enforced

like image 96
Fenton Avatar answered Oct 05 '22 22:10

Fenton


I am not satisfied how Interface doesn't enforce the method signature too. I believe the explanations by Fenton are wrong. The real reason is that Typescript is using "duck typing". No erros with less parameters, but you do get errors if you use more parameters.The long answer can be found here Why duck typing is allowed for classes in TypeScript

In the end, Interface can't fit the role of an abstract class that is extended by an other class. I wouldn't recommend to use Interface with classes but instead better use the word "implements" on an actual class, it does the same without the extra Interface class.

like image 28
Franz Avatar answered Oct 05 '22 23:10

Franz