Bird
Raised Fist0
Typescriptprogramming~20 mins

Readonly class properties in Typescript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Readonly Properties Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of readonly property assignment
What will be the output of this TypeScript code when compiled and run with strict mode?
Typescript
class Car {
  readonly brand: string;
  constructor(brand: string) {
    this.brand = brand;
  }
  changeBrand(newBrand: string) {
    this.brand = newBrand;
  }
}
const myCar = new Car('Toyota');
console.log(myCar.brand);
myCar.changeBrand('Honda');
console.log(myCar.brand);
ARuntime error when trying to assign to readonly property
BToyota\nHonda
CToyota\nToyota
DCompilation error due to assignment to readonly property
Attempts:
2 left
💡 Hint
Readonly properties cannot be assigned outside the constructor.
🧠 Conceptual
intermediate
2:00remaining
Readonly property behavior in subclasses
Consider this TypeScript code. What will be the output when running it?
Typescript
class Animal {
  readonly species: string = 'Unknown';
  constructor(species?: string) {
    if (species) this.species = species;
  }
}
class Dog extends Animal {
  constructor() {
    super('Canine');
    this.species = 'Dog';
  }
}
const pet = new Dog();
console.log(pet.species);
ACompilation error due to assignment to readonly property in subclass
BDog
CRuntime error due to assignment to readonly property
DCanine
Attempts:
2 left
💡 Hint
Readonly properties can only be assigned once, typically in the constructor of the declaring class.
🔧 Debug
advanced
2:00remaining
Why does this readonly property assignment fail?
This TypeScript code fails to compile. Identify the cause of the error.
Typescript
class Book {
  readonly title: string;
  constructor(title: string) {
    this.title = title;
  }
  rename(newTitle: string) {
    this.title = newTitle;
  }
}
const novel = new Book('1984');
novel.rename('Animal Farm');
A'title' is not initialized in the constructor
BCannot assign to 'title' because it is a readonly property
CMethod rename is not allowed in class with readonly properties
DNo error, code runs and outputs 'Animal Farm'
Attempts:
2 left
💡 Hint
Readonly properties cannot be changed after initial assignment.
📝 Syntax
advanced
2:00remaining
Identify the syntax error with readonly property
Which option contains a syntax error related to readonly class properties?
Aclass User { readonly name: string; constructor() { this.name = 'Alice'; } changeName() { this.name = 'Bob'; } }
Bclass User { readonly name: string; constructor() { this.name = 'Alice'; } }
Cclass User { readonly name: string = 'Alice'; constructor() { this.name = 'Bob'; } }
Dclass User { readonly name = 'Alice'; constructor() {} }
Attempts:
2 left
💡 Hint
Check where readonly properties are assigned.
🚀 Application
expert
3:00remaining
Readonly properties with parameter properties
What will be the output of this TypeScript code?
Typescript
class Point {
  constructor(readonly x: number, readonly y: number) {}
  move(newX: number, newY: number) {
    this.x = newX;
    this.y = newY;
  }
}
const p = new Point(5, 10);
console.log(`${p.x},${p.y}`);
p.move(20, 30);
console.log(`${p.x},${p.y}`);
A5,10\n5,10
B5,10\n20,30
CCompilation error due to assignment to readonly properties
DRuntime error when trying to assign to readonly properties
Attempts:
2 left
💡 Hint
Readonly parameter properties cannot be reassigned after construction.

Practice

(1/5)
1. What does the readonly keyword do when used on a class property in TypeScript?
easy
A. It allows the property to be changed anytime.
B. It makes the property private and inaccessible outside the class.
C. It prevents the property from being changed after initialization.
D. It deletes the property after the constructor runs.

Solution

  1. Step 1: Understand the purpose of readonly

    The readonly keyword marks a property so it cannot be changed after it is set initially.
  2. Step 2: Check when assignment is allowed

    Assignment to a readonly property is only allowed during declaration or inside the constructor.
  3. Final Answer:

    It prevents the property from being changed after initialization. -> Option C
  4. Quick Check:

    Readonly means fixed value after set [OK]
Hint: Readonly means value can't change after constructor [OK]
Common Mistakes:
  • Thinking readonly makes property private
  • Assuming readonly allows changes anytime
  • Confusing readonly with deleting properties
2. Which of the following is the correct way to declare a readonly property id of type number in a TypeScript class?
easy
A. id: readonly number;
B. readonly id: number;
C. let readonly id: number;
D. const id: number;

Solution

  1. Step 1: Recall TypeScript readonly syntax

    The correct syntax places readonly before the property name and type.
  2. Step 2: Check each option

    readonly id: number; matches the correct syntax: readonly id: number;. Others misuse keywords or order.
  3. Final Answer:

    readonly id: number; -> Option B
  4. Quick Check:

    Readonly keyword before property name [OK]
Hint: Put readonly before property name, not after type [OK]
Common Mistakes:
  • Using const inside class properties
  • Placing readonly after the type
  • Combining let with readonly incorrectly
3. What will be the output of this TypeScript code?
class User {
  readonly name: string;
  constructor(name: string) {
    this.name = name;
  }
  changeName(newName: string) {
    // @ts-ignore
    this.name = newName;
  }
}
const user = new User('Alice');
user.changeName('Bob');
console.log(user.name);
medium
A. Alice
B. undefined
C. Compilation error
D. Bob

Solution

  1. Step 1: Understand readonly assignment rules

    The name property is readonly and assigned in the constructor, so initial value is 'Alice'. TypeScript enforces this at compile-time.
  2. Step 2: Analyze the changeName method

    The @ts-ignore suppresses the TypeScript compile error for assigning to readonly. The code compiles to plain JavaScript, where objects are mutable, so this.name = newName; sets it to 'Bob' at runtime.
  3. Final Answer:

    Bob -> Option D
  4. Quick Check:

    Readonly is compile-time only; runtime allows changes [OK]
Hint: Readonly bypassed at runtime via @ts-ignore [OK]
Common Mistakes:
  • Thinking readonly prevents runtime changes
  • Expecting compilation error despite @ts-ignore
  • Believing output remains 'Alice'
4. Identify the error in this TypeScript class:
class Product {
  readonly price: number;
  constructor() {
    // No assignment to price here
  }
}
const p = new Product();
p.price = 100;
medium
A. Error: readonly property 'price' is not initialized.
B. Error: Cannot assign to 'price' outside constructor.
C. No error, code runs fine.
D. Error: price must be declared as private.

Solution

  1. Step 1: Check readonly property initialization

    The readonly property price must be assigned during declaration or in the constructor.
  2. Step 2: Analyze constructor and assignment

    The constructor does not assign price, so TypeScript reports an error about missing initialization.
  3. Final Answer:

    Error: readonly property 'price' is not initialized. -> Option A
  4. Quick Check:

    Readonly props must be initialized at declaration or constructor [OK]
Hint: Always initialize readonly properties in constructor or declaration [OK]
Common Mistakes:
  • Trying to assign readonly property after construction
  • Ignoring missing initialization error
  • Confusing readonly with private
5. Given this class, how can you safely allow updating the version property while keeping id readonly?
class Document {
  readonly id: string;
  version: number;
  constructor(id: string, version: number) {
    this.id = id;
    this.version = version;
  }
}
hard
A. Keep id readonly and update version normally via a method.
B. Make both id and version readonly and update via constructor only.
C. Remove readonly from id to allow all updates.
D. Make version readonly and update id instead.

Solution

  1. Step 1: Understand readonly usage

    The id should remain readonly to keep it fixed after creation.
  2. Step 2: Allow version updates

    The version property is not readonly, so it can be updated safely anytime, for example via a method.
  3. Final Answer:

    Keep id readonly and update version normally via a method. -> Option A
  4. Quick Check:

    Readonly for fixed, normal for changeable [OK]
Hint: Readonly for fixed props, normal for changeable ones [OK]
Common Mistakes:
  • Making all properties readonly and losing flexibility
  • Removing readonly from fixed properties
  • Confusing which property should be updated
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