In JavaScript ES6, classes support different types of members, such as methods and properties. TypeScript enriches that by bringing fields, read-only fields, and static members. Consider the following example:
class SumCalculator {
static readonly supportedOperand = Operand.Sum;
private _history: Calculable[] = [];
get history() { return this._history; }
set history(value: Calculable[]) {
this._history = value || [];
}
constructor(private readonly logPrefix: string) { }
logHistory() {
console.log(
`${this.logPrefix}: current history length: ${this.history.length}`);
}
}
console.log(SumCalculator.supportedOperand);
const calc = new SumCalculator(‘MyApp');
calc.history = [{left: 2, right: 3}];
calc.logHistory();
In the preceding code, you can see different usages of properties, static, and read-only members:
- supportedOperand is a static and a read-only member. Static, just like in C#, means that the member is allocated and accessed at the class-level and not per class instance, that is, SumCalculator.supportedOperand.
- history is a property with a getter and a setter on top of the private _history field. In the setter, it makes sure that the history is not set to null.
- logPrefix is a constructor argument that is set as a private and a readonly field, thanks to the support of TypeScript for such shorthand techniques.