Optional & Readonly Properties
Learn how to mark object and interface properties as optional or immutable.
Reading Time
12 min
Lesson
Lesson 14 of 30
Optional Properties
A property marked with ? may be omitted entirely. Its type automatically includes undefined as a possible value.
Optional Properties Example
interface Profile {
username: string;
bio?: string;
}
const profile1: Profile = { username: "alice" };
const profile2: Profile = { username: "bob", bio: "Loves TypeScript" };Checking Optional Properties Before Use
Because an optional property might be undefined, TypeScript requires you to check for its presence before using it in a way that would fail on undefined.
Safely Using an Optional Property
function printBio(profile: Profile) {
if (profile.bio) {
console.log(profile.bio.toUpperCase());
}
// or with optional chaining:
console.log(profile.bio?.toUpperCase() ?? "No bio provided");
}Readonly Properties
A property marked readonly can be set once, typically at creation, but can never be reassigned afterward.
Readonly Properties Example
interface Point {
readonly x: number;
readonly y: number;
}
const origin: Point = { x: 0, y: 0 };
origin.x = 10; // Error: Cannot assign to 'x' because it is a read-only propertyreadonly Arrays
Arrays can be made readonly too, preventing mutating methods like push() or sort() from being called, while still allowing you to read from them.
Readonly Arrays
const tags: readonly string[] = ["typescript", "javascript"];
tags.push("react"); // Error: Property 'push' does not exist on type 'readonly string[]'
console.log(tags[0]); // OK — reading is finereadonly is a Compile-Time Guarantee Only
Like all TypeScript types, readonly is erased at compile time. It prevents mistakes in your own TypeScript code, but doesn’t truly freeze the object at runtime the way Object.freeze() does.
Best Practice
Mark properties readonly whenever they represent identity or configuration that should never change after creation — it communicates intent clearly and catches accidental mutation early.