To add a setter to a subclass in TypeScript, we can define a setter in the subclass and use the super
keyword to access and set the value of the property in the parent class. Here's an example:
index.ts481 chars33 lines
In this example, the Employee
class extends the Person
class and defines a salary
property with a getter and a setter. The super
keyword is used in the constructor of the Employee
class to call the constructor of the parent class and pass the name
argument to it.
To set the value of the name
property in the Person
class from the Employee
class, we can use the super
keyword in the set
method of the name
property, like this:
index.ts152 chars9 lines
In this example, the set
method of the name
property in the Employee
class assigns the new value of name
to the name
property in the Person
class using super.name = name;
. This allows us to reuse the name
property implementation from the parent class and add additional logic specific to the Employee
class.
gistlibby LogSnag