In TypeScript, you can define a property in a class using traditional field declarations or by using TypeScript’s property accessors, which allow you to define getters and setters. Here’s how you can do both:
You can declare properties directly in the class without explicitly defining getters and setters:
class MyClass {
myProperty: number = 0;
}
const instance = new MyClass();
console.log(instance.myProperty); // Access the property
instance.myProperty = 42; // Modify the property
console.log(instance.myProperty);
In this example, myProperty is a public property with an initial value of 0. You can access and modify it directly.
Using Property Accessors (Getters and Setters):
TypeScript also supports defining properties using property accessors:
class MyClass {
private _myProperty: number = 0;
get myProperty(): number {
return this._myProperty;
}
set myProperty(value: number) {
if (value >= 0) {
this._myProperty = value;
} else {
console.error("Property value must be non-negative.");
}
}
}
const instance = new MyClass();
console.log(instance.myProperty); // Get property
instance.myProperty = 42; // Set property
console.log(instance.myProperty);
In this example, we define a private property _myProperty and create a getter and setter for myProperty. The getter allows you to retrieve the value, and the setter allows you to modify it. Private properties are indicated as private by prefixing them with an underscore.
Using property accessors with getters and setters gives you more control over how the property is accessed and modified, and it allows you to add validation or additional logic when getting or setting the property value. Choose the method that best fits your needs, depending on whether you require additional control or simply want a straightforward property with no special behavior.