0
0
Typescriptprogramming~15 mins

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

Choose your learning style9 modes available
Readonly properties in interfaces
📖 Scenario: Imagine you are creating a simple app to manage book information. Some details about a book, like its title and author, should never change once set.
🎯 Goal: You will create an interface with readonly properties to protect book details from being changed accidentally.
📋 What You'll Learn
Create an interface called Book with readonly properties
Define readonly properties title and author as strings
Create a variable myBook of type Book with specific values
Try to change a readonly property and observe the error
Print the book details
💡 Why This Matters
🌍 Real World
Readonly properties are useful when you want to make sure some data, like book titles or user IDs, do not change accidentally in your program.
💼 Career
Understanding readonly properties helps you write safer TypeScript code, which is important for many software development jobs that use TypeScript.
Progress0 / 4 steps
1
Create the Book interface with readonly properties
Create an interface called Book with readonly string properties title and author.
Typescript
Need a hint?

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

2
Create a variable myBook of type Book
Create a variable called myBook of type Book and assign it an object with title set to "The Hobbit" and author set to "J.R.R. Tolkien".
Typescript
Need a hint?

Use const myBook: Book = { title: "The Hobbit", author: "J.R.R. Tolkien" }.

3
Try to change a readonly property
Add a line that tries to change myBook.title to "The Lord of the Rings". This should cause a TypeScript error because title is readonly.
Typescript
Need a hint?

Try to assign a new value to myBook.title. TypeScript will warn you.

4
Print the book details
Write a console.log statement to print myBook.title and myBook.author in the format: "Title: The Hobbit, Author: J.R.R. Tolkien".
Typescript
Need a hint?

Use console.log(`Title: ${myBook.title}, Author: ${myBook.author}`) to print the details.