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.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.
Awesome!
Completion rate improved to 5
Getters and Setters
Veeg om het menu te tonen
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.
Bedankt voor je feedback!