0
0
Typescriptprogramming~10 mins

Getter and setter with types in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a getter for the property 'name' with type string.

Typescript
class Person {
  private _name: string;

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

  get name(): [1] {
    return this._name;
  }
}
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong return type like 'number' or 'boolean' for the getter.
Omitting the return type annotation.
2fill in blank
medium

Complete the code to declare a setter for the property 'age' with type number.

Typescript
class Person {
  private _age: number;

  set age(value: [1]) {
    this._age = value;
  }
}
Drag options to blanks, or click blank then click option'
Anumber
Bstring
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong parameter type like 'string' or 'boolean' for the setter.
Omitting the parameter type annotation.
3fill in blank
hard

Fix the error in the setter to correctly type the parameter as a boolean.

Typescript
class Light {
  private _isOn: boolean;

  set isOn(value: [1]) {
    this._isOn = value;
  }
}
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'string' or 'number' instead of 'boolean' for the setter parameter.
Leaving the parameter type as 'any' which is less safe.
4fill in blank
hard

Fill both blanks to create a getter and setter for 'score' with type number.

Typescript
class Game {
  private _score: number;

  get score(): [1] {
    return this._score;
  }

  set score(value: [2]) {
    this._score = value;
  }
}
Drag options to blanks, or click blank then click option'
Anumber
Bstring
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for getter and setter.
Using 'string' or 'boolean' instead of 'number'.
5fill in blank
hard

Fill all three blanks to create a class with a private string property '_title', and getter and setter for 'title' with correct types.

Typescript
class Book {
  private _title: [1];

  constructor(title: [2]) {
    this._title = title;
  }

  get title(): [3] {
    return this._title;
  }

  set title(value: [3]) {
    this._title = value;
  }
}
Drag options to blanks, or click blank then click option'
Astring
Bnumber
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using different types for property, constructor, getter, or setter.
Omitting type annotations.