Read-Only Properties
Some properties should never change once the object exists: a hero's name, an item's id number. Mark them readonly:
type Hero = { readonly name: string; health: number };
const kira: Hero = { name: "Kira", health: 50 };
kira.health = 40;
kira.name = "Bruno";main.ts(5,6): error TS2540: Cannot assign to 'name' because it is a read-only property.health may change, so line 4 is fine. name may not: Cannot assign to 'name' because it is a read-only property. You can still read it, print it or pass it to a function. Its value is set once, when the object is created.
How is that different from const? const protects the variable: kira must always hold the same object. The object's properties can still change, though. You may remember from the JavaScript course that this works:
const kira = { name: "Kira", health: 50 };
kira.name = "Bruno";
console.log(kira);This prints:
{ name: "Bruno", health: 50 }readonly protects one property, whichever variable the object is in, even one created with let, and also inside functions that get the object as an argument.
Like every type, readonly is checked only by TypeScript, and it disappears from the JavaScript that runs. At run time, nothing would stop the change. But a program with such a change doesn't get to run, because TypeScript reports it first.
Typical mistakes:
constinstead ofreadonlyin the type:{ const name: string }gives';' expected.In a type, the word isreadonly.- Changing the property with
+=or++: that's a change too.kira.name += "!"gives the same error askira.name = "Bruno".
Instructions
The name shouldn't change. Make name read-only. TypeScript then shows the line in levelUp that changes the name: delete it, because the level is already stored in level. The program prints Kira is level 4.
Every hero in the guild has an id number that never changes. Add a read-only property id of type number to Hero. TypeScript then reports Kira, who has no id: give her the id 7.
At the end of the program, print the line below, using kira.id, kira.name and kira.level:
#7 Kira, level 4Start programming for free
5/10