0
0
Typescriptprogramming~15 mins

Readonly properties in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Readonly properties
📖 Scenario: You are creating a simple program to store information about a book. Some details about the book should not be changed once set, like its title and author.
🎯 Goal: Build a TypeScript program that uses readonly properties to protect the book's title and author from being changed after creation.
📋 What You'll Learn
Create an interface with readonly properties
Create an object that implements the interface
Try to modify a readonly property (should cause error if uncommented)
Print the book's title and author
💡 Why This Matters
🌍 Real World
Readonly properties are useful when you want to protect important data from accidental changes, like product IDs, user IDs, or configuration settings.
💼 Career
Understanding readonly properties helps you write safer and more predictable code, which is important in professional software development to avoid bugs.
Progress0 / 4 steps
1
Create an interface with readonly properties
Create an interface called Book with two readonly properties: title and author, both of type string.
Typescript
Need a hint?

Use the readonly keyword before the property name inside the interface.

2
Create a book object implementing the interface
Create a constant called myBook of type Book and assign it an object with title set to "The TypeScript Guide" and author set to "Jane Doe".
Typescript
Need a hint?

Use const myBook: Book = { title: "The TypeScript Guide", author: "Jane Doe" };

3
Try to modify a readonly property
Add a line that tries to change myBook.title to "New Title". Comment out this line to avoid errors but keep it in the code to show the attempt.
Typescript
Need a hint?

Write myBook.title = "New Title"; and comment it out with // at the start.

4
Print the book's title and author
Write a console.log statement to print the book's title and author in the format: "Title: The TypeScript Guide, Author: Jane Doe".
Typescript
Need a hint?

Use a template string with console.log to print the message.