Reputation: 25
As in topic, why do I need to re-declare the types on the properties in a class implementing an interface declaring the same properties?
I was certain a class implementing the interface would inherit the types, but it seems the compiler only checks whether all specified properties or methods exist. Is it a bug or am I misunderstanding how interfaces work in typescript?
For example:
1) Everything is fine, but the types have to be declared twice
2) The types are declared only once, resulting in type any
3) When different type is changed from number to string, typescript correctly checks the type.
I was expecting 3) but I am surprised number 2) shows type any. This behaviour is slightly confusing to me, I would appreciate some clarification. Thank you for your help.
Upvotes: 1
Views: 404
Reputation: 30879
Implementing an interface does not inherit the types. This is discussed here and here and in the linked issues; I spent a few minutes digging but was unable to find a concise statement of the original reason. Anyway, changing this behavior now would be a breaking change.
A workaround is to write an interface that merges with the class (maybe not recommended if you are using strictPropertyInitialization
, as this seems to bypass it):
interface Point extends IPoint {}
class Point implements IPoint { ... }
Upvotes: 1