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.
Takk for tilbakemeldingene dine!
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Can you explain how getters and setters improve code safety?
What are some common use cases for getters and setters in TypeScript?
Can you show an example of adding validation logic in a setter?
Awesome!
Completion rate improved to 5
Getters and Setters
Sveip for å vise menyen
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.
Takk for tilbakemeldingene dine!