Getter and setter with types
📖 Scenario: You are creating a simple TypeScript class to manage a user's profile information. You want to control how the user's age is accessed and updated using getter and setter methods with proper type annotations.
🎯 Goal: Build a TypeScript class called UserProfile that uses a getter and setter for the age property with type safety.
📋 What You'll Learn
Create a class called
UserProfile with a private property _age of type number.Add a getter method called
age that returns the value of _age.Add a setter method called
age that accepts a number and sets the value of _age.Create an instance of
UserProfile and set the age to 30 using the setter.Print the age using the getter.
💡 Why This Matters
🌍 Real World
Getter and setter methods help protect data inside objects and allow controlled access, which is common in real-world software to keep data safe and consistent.
💼 Career
Understanding getters and setters with types is important for writing clean, maintainable TypeScript code, a skill useful for frontend and backend development jobs.
Progress0 / 4 steps