To override a setter on a subclass in TypeScript, you simply define a setter on the subclass with the same name as the parent, and then invoke super
inside of it to call the parent's implementation.
Consider the following example:
index.ts358 chars22 lines
In this example, we have a base Animal
class with a name
property, which has a getter and setter. We then define a Dog
class which extends Animal
, and overrides the name
setter to convert the name to uppercase.
When we create a new Dog
instance and set its name to "Fido"
, the overridden setter is invoked, which calls super.name = value.toUpperCase();
to set the name on the parent Animal
class with an uppercase string.
We then log the name
property of the myDog
instance, and see that it has been converted to "FIDO"
.
gistlibby LogSnag