In TypeScript, you can add a setter to a class using the set
keyword followed by the name of the property you want to set.
Here's an example that demonstrates how to add a setter to a class:
index.ts226 chars15 lines
In the example above, we define a Person
class with a private _age
property. We then define a getter and a setter for the age
property.
The get age()
method returns the value of the _age
property, while the set age(value: number)
method sets the value of _age
if it falls within a valid range (between 0 and 120 in this example).
To set the age of a Person
object, we can simply assign a value to the age
property:
index.ts85 chars4 lines
Note that if we try to assign an invalid age (e.g. a negative number or a number greater than 120), the setter will throw an error.
gistlibby LogSnag