I started learning typescript a few days ago. I know all the major OOP concepts, but I just don't understand the concept behind abstract properties. I understand that you have to override/implement the abstract members of your base class in the child class. But still, what is it used for? I get the concept behind abstract methods, but not this. If you could present me some nice examples, I would really appreciate it.
Thank you!
Abstract properties are useful for similar reasons that abstract methods are; a readonly property is conceptually similar in purpose to a getter method, so an abstract readonly property is a bit like having an abstract getter method.
For one example, imagine you have a tree structure for representing expressions: you might have an abstract class for binary expressions, and to avoid duplication, the toString
method might want to make use of a this.op
string property for the appropriate symbol to use in the string representation (e.g. '+'
). The code below shows two classes in a possible hierarchy:
abstract class MyBinaryExpr extends MyExpr {
constructor(readonly left: MyExpr, readonly right: MyExpr) { super(); }
abstract readonly op: string;
toString(): string {
return '(' + this.left + this.op + this.right + ')';
}
}
class MyAdd extends MyBinaryExpr {
op = '+';
compute(): number {
return this.left.compute() + this.right.compute();
}
}
If the same code were written in a language like Java where properties cannot be abstract, the MyBinaryExpr
class would probably have a method like abstract String getOp()
for the same purpose.
Another thing worth noting specifically in comparison to Java is that in Java, having abstract methods only makes sense because method calls in Java are dynamically dispatched to the concrete method belonging to the object's class at runtime. When some code calls an abstract method, the call cannot (in general) be bound to a concrete implementation at compile-time, so the concrete method must be selected at runtime.
On the other hand, field accesses like obj.field
in Java are statically bound at compile-time to the field declaration belonging to a class according to the compile-time type of the expression obj
. So a Java interface cannot have abstract fields because the compiler wouldn't know which actual field declaration to bind to at compile-time. So Java's semantics do not allow for abstract fields. On the other hand, Javascript (and hence Typescript) resolve all member accesses at runtime, so even property accesses are dynamically bound. Hence the semantics allow for interfaces to have abstract properties.
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