0
0
Typescriptprogramming~10 mins

Readonly class properties 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 readonly property in a TypeScript class.

Typescript
class Person {
  readonly name: string;
  constructor(name: string) {
    this.[1] = name;
  }
}
Drag options to blanks, or click blank then click option'
Aname
Bage
Creadonly
Dthis
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign to a property not declared in the class.
Using readonly keyword in the constructor assignment.
2fill in blank
medium

Complete the code to prevent modification of a readonly property after initialization.

Typescript
class Car {
  readonly model: string;
  constructor(model: string) {
    this.model = model;
  }

  changeModel(newModel: string) {
    // This line should cause an error
    this.model [1] newModel;
  }
}
Drag options to blanks, or click blank then click option'
A=
B+=
C===
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using comparison operators instead of assignment.
Trying to modify readonly property without error.
3fill in blank
hard

Fix the error in the class by correctly declaring a readonly property with an initial value.

Typescript
class Book {
  [1] title: string = "Unknown";
}
Drag options to blanks, or click blank then click option'
Aconst
Breadonly
Cprivate
Dstatic
Attempts:
3 left
💡 Hint
Common Mistakes
Using const inside a class property declaration.
Confusing private with readonly.
4fill in blank
hard

Fill both blanks to create a readonly property with a default value and a method to read it.

Typescript
class User {
  [1] id: number = 0;

  getId() {
    return this.[2];
  }
}
Drag options to blanks, or click blank then click option'
Areadonly
Bprivate
Cid
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using private instead of readonly.
Returning a property name that does not exist.
5fill in blank
hard

Fill all three blanks to declare a readonly property, initialize it via constructor shorthand, and access it in a method.

Typescript
class Product {
  constructor([1] readonly [2]: string) {}

  display() {
    console.log(this.[3]);
  }
}
Drag options to blanks, or click blank then click option'
Apublic
BproductName
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the property in constructor and method.
Omitting the readonly keyword in constructor shorthand.