interface BaseInter{ name : string; test(); } abstract class Abs implements baseInter{ }
In TypeScript, compiler complaints that the class incorrectly implements the interface:
name is missing in type abs.
Here Abs
is an abstract class and so why do we need to implement the interface over there?
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.
Abstract methods do not have the body they only have declaration but no definition. The definition is defined by implementing classes. So we look at all the examples where a method can exist with its behavior (body) inside the interface.
If you don't implement all methods of your interface, than you destroy the entire purpose of an interface. Show activity on this post.
And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it. Hence, if you want to prevent instantiation of a class directly you can declare it abstract.
You need to re-write all of the members/methods in the interface and add the abstract
keyword to them, so in your case:
interface baseInter { name: string; test(); } abstract class abs implements baseInter { abstract name: string; abstract test(); }
(code in playground)
There was a suggestion for it: Missing property declaration in abstract class implementing interfaces but it was declined for this reason:
Although, the convenience of not writing the declaration would be nice, the possible confusion/complexity arising from this change would not warrant it. by examine the declaration, it is not clear which members appear on the type, is it all properties, methods, or properties with call signatures; would they be considered abstract? optional?
You can get what you want with a slight trick that defeats the compile-time errors:
interface baseInter { name : string; test(); } interface abs extends baseInter {} abstract class abs implements baseInter{ }
This trick takes advantage of Typescript's Declaration Merging, and was originally presented here and posted on a related SO question here.
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