π Use ? to make a property optional β the object may or may not include it.
interface User {
name: string;
age?: number; // optional
}
const user1: User = { name: "Tisha" }; // β
OK
const user2: User = { name: "Tisha", age: 21 }; // β
OKπ§ You must handle the case where the property is undefined:
function printAge(user: User) {
if (user.age !== undefined) {
console.log(`Age: ${user.age}`);
} else {
console.log("Age not provided.");
}
}π Readonly Properties (readonly)
π Use readonly to prevent a property from being reassigned after initialization.
interface Config {
readonly id: string;
theme: string;
}
const appConfig: Config = {
id: "abc123",
theme: "dark"
};
appConfig.theme = "light"; // β
OK
// appConfig.id = "newId";
// β Error: Cannot assign to 'id' because it is a read-only propertyβ You can combine both!
interface Product {
readonly sku: string;
name: string;
price?: number; // optional
}
const item: Product = {
sku: "P123",
name: "Notebook"
};
// item.sku = "P124"; β Errorπ₯ Use Cases
Modifier | Purpose | Common Use Case |
|---|---|---|
| Property may be left out | Optional fields in forms or APIs |
| Property can't be reassigned after set | IDs, constants, system config values |
π§ Note
readonlyonly works on the first level β nested objects can still be modified unless their properties are also markedreadonly.Use
Readonly<T>utility type to make entire objects immutable.
type ImmutableUser = Readonly<{
name: string;
age: number;
}>;
const user: ImmutableUser = { name: "Tisha", age: 21 };
// user.name = "Riya"; // β Errorβ Summary
Modifier | Syntax | Effect |
|---|---|---|
Optional |
| Can be |
Readonly |
| Cannot be reassigned after initialization |