Skip to main content

How do you set optional fields in an interface or type?

1. Optional fields are fields that may be missing from an object

TypeScript lets you mark a property as optional by adding a question mark ? to the field name.


2. In an interface

javascript
interface User { id: number; name: string; age?: number; // ← optional field } const u1: User = { id: 1, name: "Tim" }; // age can be omitted const u2: User = { id: 2, name: "Max", age: 30 }; // age can be provided

The age field can be present or absent, but if it is present, it must be a number (number).


3. In a type (type) - exactly the same

javascript
type User = { id: number; name: string; age?: number; }; const user: User = { id: 1, name: "Tim" }; // age is not required

The behavior is fully identical to interfaces.


4. Optional fields ≠ undefined

When you write age?: number, this is equivalent to the following type:

javascript
age: number | undefined

That is, the value of age can be either a number or undefined, or missing from the object entirely.


Example:

javascript
function printUser(user: User) { console.log(user.age?.toFixed(1)); // safe: ?. checks whether age exists }

5. Optional fields in nested structures

javascript
interface Profile { name: string; address?: { city: string; zip?: string; }; } const p1: Profile = { name: "Tim" }; // address is absent const p2: Profile = { name: "Tim", address: { city: "LA" } }; // zip is absent

6. How to make all fields optional

Sometimes you need a version of a type where all fields become optional. For this, the built-in utility type Partial<T> is used:

javascript
interface User { id: number; name: string; age: number; } type UserUpdate = Partial<User>; const patch: UserUpdate = { name: "New name" }; // just one field

Partial<T> makes every property of interface T optional. This is often used for updates (updateUser(data)).


7. Optional fields and readonly

You can combine both modifiers:

javascript
interface Config { readonly host?: string; }

Here the host property:

  • may be absent,
  • but if present, it cannot be changed.

8. Optional parameters in functions (similarly)

If you need to make an optional argument, the same ? sign is used:

javascript
function greet(name?: string) { console.log(`Hi, ${name ?? "guest"}!`); } greet(); // Hi, guest! greet("Tim"); // Hi, Tim!

Here name has the type string | undefined.


Summary

WhatHow it is denotedWhat it means
Optional propertyage?: numberThe property can be number or absent
Equivalent`age: numberundefined`
Make all fields optionalPartial<Type>Makes every property ?
Used in functionsparam?: TypeThe parameter is not required when calling

Main idea:

The ? sign in TypeScript is a way to say: "This property may exist, but is not required to".

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.