Objects and Interfaces
Readonly Properties
Readonly properties can be set when an object is created and then protected from reassignment.
readonly property
`readonly` marks a property that code should not reassign after initialization.
Readonly Properties
readonly.ts
Replay: real traced execution (multi-file project)
interface CartLine {
readonly sku: string;
quantity: number;
}
const quantity: number = 2;
const line: CartLine = {
sku: "PEN-1",
quantity: quantity
};
line.quantity = line.quantity + 1;
console.log(`${line.sku}: ${line.quantity}`);
interface CartLine {
readonly sku: string;
quantity: number;
}
const quantity: number = 1;
const line: CartLine = {
sku: "PEN-1",
quantity: quantity
};
line.quantity = line.quantity + 1;
console.log(`${line.sku}: ${line.quantity}`);
interface CartLine {
readonly sku: string;
quantity: number;
}
const quantity: number = 5;
const line: CartLine = {
sku: "PEN-1",
quantity: quantity
};
line.quantity = line.quantity + 1;
console.log(`${line.sku}: ${line.quantity}`);
quantity ← 2, line ← [object Object], line.quantity ← 3
3 quantity: number;4}56const quantity→ 2: number = 2; //@quantity=1, 57const line→ [object Object]: CartLine = {8 sku: "PEN-1",9 quantity: quantity210};1112line.quantity = line.quantity→ 3 + 1;1314console.log(`${line.skuPEN-1}: ${line.quantity3}`);outputPEN-1: 3
quantity ← 1, line ← [object Object], line.quantity ← 2
3 quantity: number;4}56const quantity→ 1: number = 1;7const line→ [object Object]: CartLine = {8 sku: "PEN-1",9 quantity: quantity110};1112line.quantity = line.quantity→ 2 + 1;1314console.log(`${line.skuPEN-1}: ${line.quantity2}`);outputPEN-1: 2
quantity ← 5, line ← [object Object], line.quantity ← 6
3 quantity: number;4}56const quantity→ 5: number = 5;7const line→ [object Object]: CartLine = {8 sku: "PEN-1",9 quantity: quantity510};1112line.quantity = line.quantity→ 6 + 1;1314console.log(`${line.skuPEN-1}: ${line.quantity6}`);outputPEN-1: 6
Follow the Line
CartLinehas a readonlyskuand a mutablequantity.quantitystarts at2.lineis created as{ sku: "PEN-1", quantity: 2 }.- The code increments
line.quantityby1. - The program prints
PEN-1: 3. | starting quantity | after increment | output | | --- | --- | --- | | 1 | 2 |PEN-1: 2| | 2 | 3 |PEN-1: 3| | 5 | 6 |PEN-1: 6|
Exercise: readonly.ts
Reproduce PEN-1: 3, then use the pinned starting quantities 1 and 5 to predict each output while leaving sku unchanged.