I'd reading about typescript's class
and abstract class
and I did find something very interesting.
Typescript allows us to implement classes
.
I even created a stackblitz project to test it.
Anyway, I already found the general differences here, and what is its behavior in typescript here.
I'm aware that it can be used to create mock for tests.
Why typescript allows it, if in other very popular languages (Java
, C#
,...) it is 'forbidden'? Is There any other important application of this feature?
TypeScript has supported abstract classes since 2015, which provides compiler errors if you try to instantiate that class. TypeScript 4.2 adds support for declaring that the constructor function is abstract.
Abstract class is used when we want to give a specific implementation of our methods. In TypeScript, we can create abstract class by simply using 'abstract'keyword with it. Inside this, we can define our methods that implementation needs to be provided when implemented.
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.
Before you asked this question I didn't think about, but after I read your question it didn't let me go because I didn't know an answer as well, so I simply asked a typescript lang (core) dev via twitter and I got a reply so I will leave it here.
Twitter Source
expressed in a simple way: "if it works it ain't stupid" and they didn't disallow it because it works
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