Bird
Raised Fist0
Typescriptprogramming~20 mins

Getter and setter with types in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Getter and Setter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this TypeScript getter and setter example?

Consider this TypeScript class with typed getter and setter. What will be printed when the code runs?

Typescript
class Person {
  private _age: number = 0;

  get age(): number {
    return this._age;
  }

  set age(value: number) {
    if (value < 0) {
      this._age = 0;
    } else {
      this._age = value;
    }
  }
}

const p = new Person();
p.age = -5;
console.log(p.age);
A0
B-5
Cundefined
DTypeError
Attempts:
2 left
💡 Hint

Look at how the setter handles negative values.

❓ Predict Output
intermediate
2:00remaining
What is the output when accessing a getter without a setter?

Look at this TypeScript class with only a getter. What happens when we try to assign a value to the property?

Typescript
class Circle {
  private _radius: number = 5;

  get radius(): number {
    return this._radius;
  }
}

const c = new Circle();
c.radius = 10;
console.log(c.radius);
A5
B10
CCompilation error
DTypeError at runtime
Attempts:
2 left
💡 Hint

Think about whether you can assign to a getter-only property in TypeScript.

🔧 Debug
advanced
2:00remaining
Why does this setter cause a stack overflow error?

Examine this TypeScript class. Why does setting value cause a stack overflow?

Typescript
class Counter {
  private _count = 0;

  get count(): number {
    return this._count;
  }

  set count(value: number) {
    this.count = value; // Problem here
  }
}

const counter = new Counter();
counter.count = 5;
ABecause the setter calls itself recursively without a base case
BBecause the getter is missing a return statement
CBecause _count is not initialized
DBecause count is declared private
Attempts:
2 left
💡 Hint

Look at what happens inside the setter when assigning this.count = value.

📝 Syntax
advanced
2:00remaining
Which option correctly defines a typed getter and setter in TypeScript?

Choose the option that correctly defines a getter and setter for a name property of type string.

A
class User {
  private _name: string = '';
  get name(): string {
    return this._name;
  }
  set name(value: string) {
    return this._name = value;
  }
}
B
class User {
  private _name: string = '';
  get name() {
    return this._name;
  }
  set name(value) {
    this._name = value;
  }
}
C
class User {
  private _name: string = '';
  get name(): string {
    return this._name;
  }
  set name(value: number) {
    this._name = value;
  }
}
D
class User {
  private _name: string = '';
  get name(): string {
    return this._name;
  }
  set name(value: string) {
    this._name = value;
  }
}
Attempts:
2 left
💡 Hint

Check the types of getter return and setter parameter, and the setter body.

🚀 Application
expert
2:00remaining
How many items are in the resulting array after using a getter that returns a filtered list?

Given this TypeScript class with a getter that filters items, how many items does filteredItems contain?

Typescript
class Store {
  private items: number[] = [1, 2, 3, 4, 5, 6];

  get filteredItems(): number[] {
    return this.items.filter(x => x % 2 === 0);
  }
}

const store = new Store();
const filtered = store.filteredItems;
A6
B3
C4
D0
Attempts:
2 left
💡 Hint

Count how many even numbers are in the original array.

Practice

(1/5)
1.

What is the main purpose of using getter and setter in TypeScript classes?

easy
A. To make functions run faster
B. To create new classes automatically
C. To control how properties are accessed and modified with type safety
D. To declare variables without types

Solution

  1. Step 1: Understand getter and setter roles

    Getters and setters allow controlled access to class properties, letting you add logic when reading or writing values.
  2. Step 2: Recognize type safety benefit

    Using types with getters and setters ensures only valid data is assigned or returned, keeping data safe.
  3. Final Answer:

    To control how properties are accessed and modified with type safety -> Option C
  4. Quick Check:

    Getter and setter purpose = control access + type safety [OK]
Hint: Getters/setters control property access safely [OK]
Common Mistakes:
  • Thinking getters/setters create new classes
  • Believing they improve function speed
  • Confusing them with variable declarations
2.

Which of the following is the correct syntax to define a typed getter for a property name of type string in a TypeScript class?

class Person {
  private _name: string;

  constructor(name: string) {
    this._name = name;
  }

  // What is the correct getter syntax here?
}
easy
A. get name(): string { return this._name; }
B. get name { return this._name; }
C. getter name(): string { return this._name; }
D. get name(): void { return this._name; }

Solution

  1. Step 1: Recall getter syntax in TypeScript

    The getter uses the keyword get, followed by the property name, parentheses, and a return type.
  2. Step 2: Check return type matches property type

    The getter must return a string since _name is a string.
  3. Final Answer:

    get name(): string { return this._name; } -> Option A
  4. Quick Check:

    Getter syntax = get + name() + return type [OK]
Hint: Getter needs 'get', name(), and correct return type [OK]
Common Mistakes:
  • Omitting parentheses after getter name
  • Using wrong keyword like 'getter'
  • Setting return type to void instead of string
3.

What will be the output of the following TypeScript code?

class Counter {
  private _count: number = 0;

  get count(): number {
    return this._count;
  }

  set count(value: number) {
    if (value >= 0) {
      this._count = value;
    }
  }
}

const c = new Counter();
c.count = 5;
c.count = -3;
console.log(c.count);
medium
A. undefined
B. 5
C. 0
D. -3

Solution

  1. Step 1: Analyze setter behavior

    The setter only updates _count if the new value is >= 0. Setting to 5 updates it, setting to -3 is ignored.
  2. Step 2: Check final value returned by getter

    The getter returns the current _count, which remains 5 after the invalid -3 assignment.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Setter blocks negative, final count = 5 [OK]
Hint: Setter blocks negative values, so count stays 5 [OK]
Common Mistakes:
  • Assuming setter accepts negative values
  • Expecting count to be -3 after invalid set
  • Confusing initial value with final output
4.

Identify the error in this TypeScript class using getter and setter:

class User {
  private _age: number;

  get age(): number {
    return this._age;
  }

  set age(value: string) {
    this._age = Number(value);
  }
}
medium
A. Setter parameter type should be number, not string
B. Getter must return string, not number
C. Private property _age should be string
D. Setter cannot convert string to number

Solution

  1. Step 1: Compare getter and setter types

    The getter returns a number, so the setter should accept a number to keep types consistent.
  2. Step 2: Identify mismatch in setter parameter

    The setter takes a string but assigns to a number property, causing a type mismatch.
  3. Final Answer:

    Setter parameter type should be number, not string -> Option A
  4. Quick Check:

    Setter param type must match property type [OK]
Hint: Setter param type must match property type [OK]
Common Mistakes:
  • Allowing setter param type different from property
  • Thinking getter return type should change
  • Believing setter can't convert types
5.

Given this TypeScript class, what will console.log(user.fullName); output?

class User {
  private _firstName: string;
  private _lastName: string;

  constructor(firstName: string, lastName: string) {
    this._firstName = firstName;
    this._lastName = lastName;
  }

  get fullName(): string {
    return `${this._firstName} ${this._lastName}`;
  }

  set fullName(name: string) {
    const parts = name.split(' ');
    if (parts.length === 2) {
      [this._firstName, this._lastName] = parts;
    }
  }
}

const user = new User('Jane', 'Doe');
user.fullName = 'John Smith';
console.log(user.fullName);
hard
A. Jane Doe
B. Jane Smith
C. John Doe
D. John Smith

Solution

  1. Step 1: Understand setter logic

    The setter splits the input string by space and updates _firstName and _lastName only if there are exactly two parts.
  2. Step 2: Apply setter and check getter output

    Setting fullName to 'John Smith' updates the names. The getter then returns 'John Smith'.
  3. Final Answer:

    John Smith -> Option D
  4. Quick Check:

    Setter splits and updates names, getter returns combined string [OK]
Hint: Setter splits fullName, getter joins first and last [OK]
Common Mistakes:
  • Assuming original names stay after setter call
  • Expecting only first or last name to change
  • Ignoring setter condition on split length
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard