Getters and Setters
123456789101112131415161718192021222324class BankAccount { private _balance: number; constructor(initialBalance: number) { this._balance = initialBalance; } get balance(): number { return this._balance; } set balance(amount: number) { if (amount < 0) { throw new Error("Balance cannot be negative"); } this._balance = amount; } } const account = new BankAccount(1000); console.log(account.balance); // 1000 account.balance = 1500; console.log(account.balance); // 1500 // account.balance = -500; // This will throw an error
Getters and setters in TypeScript classes let you control how properties are accessed and modified. Instead of exposing a property directly, you can use a getter to retrieve its value and a setter to update it. This approach lets you add logic, such as validation or transformation, whenever a property is read or written. By using getters and setters, you can prevent invalid states, enforce rules, or trigger side effects, all while keeping the property itself private and protected from direct changes. This encapsulation is a key part of object-oriented programming, helping you maintain clean, predictable, and robust code as your applications grow.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione
Awesome!
Completion rate improved to 5
Getters and Setters
Scorri per mostrare il menu
123456789101112131415161718192021222324class BankAccount { private _balance: number; constructor(initialBalance: number) { this._balance = initialBalance; } get balance(): number { return this._balance; } set balance(amount: number) { if (amount < 0) { throw new Error("Balance cannot be negative"); } this._balance = amount; } } const account = new BankAccount(1000); console.log(account.balance); // 1000 account.balance = 1500; console.log(account.balance); // 1500 // account.balance = -500; // This will throw an error
Getters and setters in TypeScript classes let you control how properties are accessed and modified. Instead of exposing a property directly, you can use a getter to retrieve its value and a setter to update it. This approach lets you add logic, such as validation or transformation, whenever a property is read or written. By using getters and setters, you can prevent invalid states, enforce rules, or trigger side effects, all while keeping the property itself private and protected from direct changes. This encapsulation is a key part of object-oriented programming, helping you maintain clean, predictable, and robust code as your applications grow.
Grazie per i tuoi commenti!