How Do Optional and Readonly Properties Work in TypeScript?

Learn How Do Optional and Readonly Properties Work in TypeScript? with practical examples, explanations, best practices, and real-world coding techniques.

Introduction to Optional and Readonly Properties

TypeScript interfaces and type aliases describe the properties an object is expected to contain. However, not every property must always be available, and some properties should not be reassigned after an object has been created.

TypeScript provides two property modifiers for these situations. The question mark (?) makes a property optional, while the readonly keyword prevents ordinary reassignment through a readonly-typed reference.

These modifiers are useful for user profiles, API responses, configuration objects, application settings, records with immutable identifiers, and many other data structures. Understanding their behavior helps you describe object contracts accurately and handle missing values safely.

1. Understanding Optional Properties

By default, properties declared in an interface or object type alias are required. If a property is optional, an object can omit it while still satisfying the declared type.

Add a question mark immediately after the property name to mark it as optional.

interface User {
  id: number;
  name: string;
  email?: string;
  phone?: string;
}

const firstUser: User = {
  id: 101,
  name: "Asha",
  email: "asha@example.com"
};

const secondUser: User = {
  id: 102,
  name: "Rahul"
};

console.log(firstUser);
console.log(secondUser);

The id and name properties are required, while email and phone are optional. Both objects satisfy the User interface because they contain the required properties and use compatible types for the optional properties they provide.

Optional properties are useful when information is not always available, such as a phone number that users may choose not to provide or a description that has not yet been added to a course.

Mark a property optional only when its absence is a valid part of the data model. If an application cannot operate without a property, keeping it required gives TypeScript a stronger contract to enforce.

2. Accessing Optional Properties Safely

An optional property may be absent from an object. When you read it, TypeScript generally includes undefined in the property's possible value type under strict null checking.

interface User {
  name: string;
  email?: string;
}

const user: User = {
  name: "Asha"
};

console.log(user.email);

// Check before using the value.
if (user.email !== undefined) {
  console.log(user.email.toLowerCase());
}

The email property may not exist, so accessing a string method without checking the value can produce a runtime error. The conditional ensures that the code calls toLowerCase only when email contains a string.

TypeScript uses control-flow analysis to narrow the property's type inside the condition. After the check, the compiler can treat user.email as a string for that code path.

You can also use optional chaining when accessing a property of an optional object or value. For example, user.email?.toLowerCase() returns undefined if email is null or undefined instead of attempting to call the method.

Optional chaining is useful when skipping an operation is acceptable. If the application must display a value or report an error when the property is missing, use an explicit check or provide an appropriate fallback instead.

3. Using Nullish Coalescing with Optional Properties

The nullish coalescing operator (??) provides a fallback when an expression evaluates to null or undefined. It is useful when reading optional properties that need a default display value or processing value.

interface Course {
  id: number;
  title: string;
  description?: string;
  duration?: number;
}

const course: Course = {
  id: 101,
  title: "TypeScript Fundamentals"
};

const description = course.description ?? "No description available";
const duration = course.duration ?? 0;

console.log(description);
console.log(duration);

Since description and duration are missing, the fallback values are used. If duration were zero, the expression duration ?? 0 would preserve zero because zero is not null or undefined.

This differs from the logical OR operator (||), which uses the fallback when the left side is any falsy value, including zero, an empty string, or false.

const duration = 0;

console.log(duration || 30); // 30
console.log(duration ?? 30); // 0

Prefer ?? when only missing values should trigger the fallback. This is particularly important for numeric settings, Boolean options, and text fields where zero, false, or an empty string may be meaningful.

4. Understanding Readonly Properties

The readonly modifier prevents a property from being reassigned through a reference whose type declares that property readonly. This is useful for fields such as identifiers that should not be changed during ordinary use of an object.

interface Course {
  readonly id: number;
  title: string;
}

const course: Course = {
  id: 101,
  title: "TypeScript"
};

course.title = "Advanced TypeScript";

// Compile-time error:
// course.id = 202;

console.log(course.id);
console.log(course.title);

The id property is readonly, so TypeScript rejects its reassignment through the course reference. The title property is writable and can be updated normally.

Readonly is a compile-time restriction. It does not automatically freeze the JavaScript object or prevent every possible modification through untyped code or another mutable reference.

It is also shallow. If a readonly property refers to an object, the reference cannot normally be replaced through that property, but nested properties may remain mutable unless they are also described as readonly.

Use readonly to communicate that a property should not be reassigned through a particular typed reference. When runtime immutability is required, use an appropriate runtime design rather than relying on readonly alone.

5. Combining Optional and Readonly Modifiers

A property can be both optional and readonly. This means an object does not have to provide the property, but ordinary reassignment through the readonly-typed reference is prohibited once the object has been initialized.

interface User {
  readonly id: number;
  readonly createdAt?: Date;
  name: string;
}

const user: User = {
  id: 101,
  name: "Asha"
};

user.name = "Asha Rao";

// Compile-time error:
// user.id = 202;

// Compile-time error:
// user.createdAt = new Date();

console.log(user);

The id property is required and readonly. The createdAt property is optional and readonly, so the object can omit it but cannot ordinarily assign it through the user reference after initialization.

The name property is required and writable. It can be changed after the object is created.

This combination is useful for records that have immutable identifiers or creation metadata but allow other fields to be edited. Be careful when updating such objects because the original object's type may not permit assigning new values to readonly properties.

6. Optional and Readonly Properties in Type Aliases

Optional and readonly modifiers are not limited to interfaces. They can also be used in object types declared with the type keyword.

type AppConfig = {
  readonly appName: string;
  apiBaseUrl: string;
  debug?: boolean;
};

const config: AppConfig = {
  appName: "IgKnight",
  apiBaseUrl: "/api"
};

config.apiBaseUrl = "/v2/api";
config.debug = true;

// Compile-time error:
// config.appName = "Another Platform";

console.log(config);

The appName property is required and readonly. The apiBaseUrl property is required and writable, while debug is optional.

The behavior of these modifiers is the same whether the object contract is defined by an interface or an object type alias. You can choose either construct according to the broader needs of your type definition.

Type aliases are particularly useful when the object type needs to be combined with unions or intersections, while interfaces are often convenient for extensible object contracts.

7. Readonly Arrays and Tuples

TypeScript also supports readonly collections. A readonly array allows code to read its elements but prevents ordinary mutating operations through that readonly reference.

const languages: readonly string[] = [
  "HTML",
  "CSS",
  "TypeScript"
];

console.log(languages[0]);
console.log(languages.length);

// Compile-time error:
// languages.push("JavaScript");

// Compile-time error:
// languages[0] = "Python";

The readonly string[] type prevents methods such as push from being used through the languages reference, and it prevents direct indexed assignment.

A readonly tuple can also describe a fixed sequence of position-specific types without allowing ordinary mutation through that reference.

type Coordinates = readonly [number, number];

const point: Coordinates = [10, 20];

console.log(point[0]);
console.log(point[1]);

// Compile-time error:
// point[0] = 50;

// Compile-time error:
// point.push(30);

Readonly arrays and tuples are useful when collections represent constants, input data that should not be modified by a function, or sequences whose order and structure should remain stable.

These types do not make the underlying array immutable at runtime. Another mutable reference to the same array may still be able to modify it, so consider ownership and runtime requirements when designing APIs that share collections.

8. Updating Objects with Readonly Properties

Sometimes an application needs to update an object while preserving readonly properties on the original type. Instead of changing the readonly property directly, you can create a new object with the desired values.

interface User {
  readonly id: number;
  name: string;
  email?: string;
}

const user: User = {
  id: 101,
  name: "Asha"
};

const updatedUser: User = {
  ...user,
  name: "Asha Rao",
  email: "asha@example.com"
};

console.log(user);
console.log(updatedUser);

The spread operator creates a new object containing the existing properties, after which the updated name and email are supplied. The readonly id is preserved without assigning to user.id.

This approach is useful in state management, UI applications, and systems where immutable update patterns make changes easier to reason about.

Object spread performs a shallow copy. Nested objects and arrays are still shared references unless you copy or replace them separately. Readonly properties do not automatically make an entire object graph immutable.

9. Optional Properties and exactOptionalPropertyTypes

An optional property can be omitted from an object. However, whether explicitly assigning undefined is accepted depends on the property's declaration and the compiler configuration.

interface User {
  email?: string;
}

const firstUser: User = {};

// Depending on compiler configuration:
const secondUser: User = {
  email: undefined
};

Without exactOptionalPropertyTypes, an optional property is generally treated as allowing explicit undefined assignment, provided other type rules are satisfied.

When exactOptionalPropertyTypes is enabled, an optional string property means it can be absent or contain a string. Explicitly assigning undefined is not allowed unless undefined is included in the declared value type.

interface User {
  email?: string;
  displayName?: string | undefined;
}

const firstUser: User = {};

// With exactOptionalPropertyTypes enabled:
const secondUser: User = {
  displayName: undefined
};

// Compile-time error with that option enabled:
// const thirdUser: User = { email: undefined };

This distinction can matter when working with object updates, API payloads, and configuration objects. An omitted property and a property explicitly set to undefined may have different meanings in JavaScript operations such as the in operator and Object.keys.

Enable exactOptionalPropertyTypes when the distinction between a missing property and an explicitly undefined value is important to your application's type contracts.

10. Common Mistakes with Optional and Readonly Properties

Accessing optional values without checking

An optional property may be undefined. Check that the value exists or use optional chaining and nullish coalescing before applying operations that require a defined value.

Marking required properties as optional

Making every property optional weakens an interface's guarantees. Keep essential properties required so the compiler can identify incomplete objects.

Assuming readonly freezes an object

Readonly restricts reassignment through a typed reference. It does not automatically provide runtime immutability or deep protection for nested properties.

Forgetting that readonly is shallow

A readonly property that contains a mutable object may still allow changes to the object's nested members. Use readonly nested types or suitable runtime techniques if deeper immutability is required.

Using || for every fallback

The logical OR operator replaces all falsy values, including zero and false. Use nullish coalescing when only null or undefined should trigger a default.

Ignoring exactOptionalPropertyTypes

The option affects whether explicit undefined is accepted for optional properties. Understand the setting when distinguishing an omitted field from one explicitly set to undefined.

Best Practices for Optional and Readonly Properties

  • Mark properties optional only when their absence is valid for the data model.
  • Keep essential identifiers and required data fields mandatory.
  • Use readonly for properties that should not be reassigned through a particular typed reference.
  • Handle missing values with explicit checks, optional chaining, or appropriate nullish coalescing.
  • Use readonly array and tuple types when callers should not mutate collections through that reference.
  • Remember that readonly is a compile-time restriction and does not freeze an object at runtime.
  • Consider exactOptionalPropertyTypes when omitted values and explicit undefined assignments must be distinguished.
  • Use immutable update patterns when you need to create updated objects without reassigning readonly properties.
  • Validate external data at runtime rather than assuming an interface guarantees the actual object structure.

Conclusion

Optional and readonly properties allow TypeScript developers to express more precise object contracts. Optional properties represent information that may be absent, while readonly properties prevent ordinary reassignment through the corresponding typed reference.

Practise combining these modifiers in interfaces and type aliases, handling optional values safely, and using readonly collections where appropriate. Understanding compiler settings such as exactOptionalPropertyTypes also helps you model missing values correctly. These techniques make TypeScript applications more predictable while keeping their data structures clear and maintainable.

Code Examples

Optional Properties

typescript
interface User {
  id: number;
  name: string;
  email?: string;
}

const user: User = {
  id: 101,
  name: "Asha"
};

console.log(user.email);

if (user.email !== undefined) {
  console.log(user.email.toLowerCase());
}
    

The email property can be omitted. Checking it before accessing string methods ensures that the operation only runs when a string is available.

Readonly Properties

typescript
interface Course {
  readonly id: number;
  title: string;
}

const course: Course = {
  id: 101,
  title: "TypeScript"
};

course.title = "Advanced TypeScript";

// Compile-time error:
// course.id = 202;

console.log(course);
    

The readonly modifier prevents ordinary reassignment of id through the typed reference while allowing title to be updated.

Combining Optional and Readonly

typescript
interface User {
  readonly id: number;
  readonly createdAt?: Date;
  name: string;
}

const user: User = {
  id: 101,
  name: "Asha"
};

user.name = "Asha Rao";

// Compile-time error:
// user.id = 202;

// Compile-time error:
// user.createdAt = new Date();

console.log(user);
    

A property can be optional and readonly at the same time. It may be omitted from the object, but it cannot normally be reassigned through that typed reference.

Nullish Coalescing for Optional Values

typescript
interface Course {
  title: string;
  duration?: number;
}

const course: Course = {
  title: "TypeScript"
};

const duration = course.duration ?? 0;
const title = course.title ?? "Untitled";

console.log(duration);
console.log(title);

const zero = 0;

console.log(zero || 30);
console.log(zero ?? 30);
    

Nullish coalescing provides a fallback only for null or undefined. Unlike ||, it preserves valid falsy values such as zero.

Readonly Arrays and Tuples

typescript
const languages: readonly string[] = [
  "HTML",
  "CSS",
  "TypeScript"
];

type Coordinates = readonly [number, number];

const point: Coordinates = [10, 20];

console.log(languages[0]);
console.log(point[0]);
console.log(point[1]);

// Compile-time errors:
// languages.push("JavaScript");
// point[0] = 30;
    

Readonly arrays and tuples prevent ordinary mutation through their readonly references while preserving access to their values.

Creating Updated Objects

typescript
interface User {
  readonly id: number;
  name: string;
  email?: string;
}

const user: User = {
  id: 101,
  name: "Asha"
};

const updatedUser: User = {
  ...user,
  name: "Asha Rao",
  email: "asha@example.com"
};

console.log(user);
console.log(updatedUser);
    

Object spread creates a new object and preserves the readonly identifier without directly reassigning the original property.

Pro Tip

Use ? only when a property can legitimately be absent, and use readonly when callers should not reassign it through a particular typed reference. Handle optional values explicitly, prefer ?? when zero or false are valid values, and remember that readonly does not provide runtime or deep immutability.

More TypeScript lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.