TypeScript
Beginner
1 min read
Getters, Setters, and the Singleton Pattern
Example
// Getters and setters
class Temperature {
private _celsius: number;
constructor(celsius: number) {
this._celsius = celsius;
}
get celsius(): number { return this._celsius; }
set celsius(value: number) {
if (value < -273.15) throw new RangeError("Below absolute zero");
this._celsius = value;
}
get fahrenheit(): number { return this._celsius * 9 / 5 + 32; }
set fahrenheit(value: number) { this.celsius = (value - 32) * 5 / 9; }
get kelvin(): number { return this._celsius + 273.15; }
}
const t = new Temperature(100);
console.log(t.fahrenheit); // 212
t.fahrenheit = 32;
console.log(t.celsius); // 0
// Singleton pattern with private constructor
class AppConfig {
private static instance: AppConfig | null = null;
private constructor(
public readonly apiUrl: string,
public readonly debug: boolean,
) {}
static getInstance(): AppConfig {
if (!AppConfig.instance) {
AppConfig.instance = new AppConfig(
process.env["API_URL"] ?? "https://api.example.com",
process.env["NODE_ENV"] !== "production",
);
}
return AppConfig.instance;
}
}
const cfg1 = AppConfig.getInstance();
const cfg2 = AppConfig.getInstance();
console.log(cfg1 === cfg2); // true — same instance
Related Resources
TypeScript Reference
Complete tag & property list
TypeScript How-To Guides
Step-by-step practical guides
TypeScript Exercises
Practice what you've learned
More in TypeScript