0
0
Typescriptprogramming~15 mins

Getter and setter with types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the UserProfile class with a private _age property
Create a TypeScript class called UserProfile with a private property called _age of type number initialized to 0.
Typescript
Need a hint?

Use private _age: number = 0; inside the class to create the private property.

2
Add getter and setter for age with types
Add a getter method called age that returns a number and returns this._age. Add a setter method called age that accepts a parameter value of type number and sets this._age to value.
Typescript
Need a hint?

Use get age(): number { return this._age; } and set age(value: number) { this._age = value; }.

3
Create an instance and set age using the setter
Create a variable called user as a new instance of UserProfile. Use the setter to set user.age to 30.
Typescript
Need a hint?

Create the instance with const user = new UserProfile(); and set age with user.age = 30;.

4
Print the age using the getter
Write a console.log statement to print user.age.
Typescript
Need a hint?

Use console.log(user.age); to print the age.