Book with readonly propertiestitle and author as stringsmyBook of type Book with specific valuesBook with readonly propertiestitle and author as stringsmyBook of type Book with specific valuesBook interface with readonly propertiesBook with readonly string properties title and author.Use the readonly keyword before the property name inside the interface.
myBook of type BookmyBook of type Book and assign it an object with title set to "The Hobbit" and author set to "J.R.R. Tolkien".Use const myBook: Book = { title: "The Hobbit", author: "J.R.R. Tolkien" }.
myBook.title to "The Lord of the Rings". This should cause a TypeScript error because title is readonly.Try to assign a new value to myBook.title. TypeScript will warn you.
console.log statement to print myBook.title and myBook.author in the format: "Title: The Hobbit, Author: J.R.R. Tolkien".Use console.log(`Title: ${myBook.title}, Author: ${myBook.author}`) to print the details.
What does the readonly keyword do when used in a TypeScript interface property?
readonly in interfacesreadonly keyword marks a property so it cannot be reassigned after the object is created.readonly.readonly means no changes allowed after creation [OK]Which of the following is the correct syntax to declare a readonly property id of type number in a TypeScript interface?
interface User {
?
}readonly before the property name, then a colon and the type.Consider the following code:
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 10, y: 20 };
p.x = 30;
console.log(p.x);What will happen when this code runs?
Find the error in this code snippet:
interface Config {
readonly url: string;
}
const config: Config = { url: "https://api.com" };
config.url = "https://newapi.com";url is marked readonly, so it cannot be reassigned after initialization.config.url = "https://newapi.com"; tries to change a readonly property, causing a compile-time error.You want to create an interface Person with a readonly id and a mutable name. Which code correctly enforces this?
?
readonly keyword must be before the property name to make it immutable; properties without it remain mutable.id as readonly and name as mutable. Options B, C, and D misuse readonly or make both properties readonly.Pass the test and this pattern moves unknown