📖 Scenario: Imagine you are creating a program to manage books in a library. Each book has a title and an author. Once a book is created, its title and author should never change.
🎯 Goal: You will create a TypeScript class called Book with readonly properties title and author. Then, you will create an instance of this class and display its details.
📋 What You'll Learn
Create a class named Book with readonly properties title and author
Add a constructor to Book that sets title and author
Create an instance of Book with title 'The Great Gatsby' and author 'F. Scott Fitzgerald'
Print the book's title and author using console.log
💡 Why This Matters
🌍 Real World
Readonly properties are useful when you want to protect important data from being changed after creation, like book details, user IDs, or configuration settings.
💼 Career
Understanding readonly properties helps you write safer and more predictable TypeScript code, which is valuable in many software development jobs.
Progress0 / 4 steps
1
Create the Book class with readonly properties
Create a class called Book with readonly properties title and author of type string.
Typescript
Hint
Use the readonly keyword before the property names to make them immutable.
2
Add a constructor to set the readonly properties
Add a constructor to the Book class that takes parameters title and author of type string and assigns them to the readonly properties.
Typescript
Hint
The constructor sets the readonly properties when a new Book is created.
3
Create an instance of Book
Create a variable called myBook and assign it a new Book object with title 'The Great Gatsby' and author 'F. Scott Fitzgerald'.
Typescript
Hint
Use the new keyword to create an instance of the Book class.
4
Print the book's title and author
Use console.log to print the book's title and author from the myBook object in the format: Title: The Great Gatsby, Author: F. Scott Fitzgerald.
Typescript
Hint
Use a template string with backticks and ${} to insert the property values.
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
Step 1: Understand the purpose of readonly
The readonly keyword marks a property so it cannot be changed after it is set initially.
Step 2: Check when assignment is allowed
Assignment to a readonly property is only allowed during declaration or inside the constructor.
Final Answer:
It prevents the property from being changed after initialization. -> Option C
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
Step 1: Recall TypeScript readonly syntax
The correct syntax places readonly before the property name and type.
Step 2: Check each option
readonly id: number; matches the correct syntax: readonly id: number;. Others misuse keywords or order.
Final Answer:
readonly id: number; -> Option B
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
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.
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.
Final Answer:
Bob -> Option D
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
Step 1: Check readonly property initialization
The readonly property price must be assigned during declaration or in the constructor.
Step 2: Analyze constructor and assignment
The constructor does not assign price, so TypeScript reports an error about missing initialization.
Final Answer:
Error: readonly property 'price' is not initialized. -> Option A
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?