Careeroza
Optional and Readonly Properties
Optional Properties
Add ? after a property name to make it optional. Its type then includes undefined, so you must check before using it.
Example
type Address = {
line1: string;
line2?: string;
city: string;
landmark?: string;
};
function format(a: Address): string {
const parts = [a.line1, a.line2, a.city];
if (a.landmark) parts.push("near " + a.landmark);
return parts.filter(Boolean).join(", ");
}
console.log(format({ line1: "12 MG Road", city: "Pune" }));
console.log(format({ line1: "Flat 5B", line2: "Lake View Apts", city: "Kochi", landmark: "Metro" }));Output
12 MG Road, Pune Flat 5B, Lake View Apts, Kochi, near Metro
Readonly Properties
Example
A readonly property can be set when the object is created but not changed later (TS2540).
type Order = {
readonly id: string;
status: string;
};
const order: Order = { id: "OD-1", status: "PLACED" };
order.status = "SHIPPED"; // fine
order.id = "OD-2"; // errorCompiler output (tsc)
Line 8: error TS2540: Cannot assign to 'id' because it is a read-only property.
Tip: Mark IDs, creation dates and other never-changing fields as readonly. It documents intent and prevents accidental writes.