0
0
Typescriptprogramming~15 mins

Readonly class properties in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Readonly class properties
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use a template string with backticks and ${} to insert the property values.