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
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 providedThe
agefield can be present or absent, but if it is present, it must be a number (number).
3. In a type (type) - exactly the same
type User = {
id: number;
name: string;
age?: number;
};
const user: User = { id: 1, name: "Tim" }; // age is not requiredThe behavior is fully identical to interfaces.
4. Optional fields ≠ undefined
When you write age?: number, this is equivalent to the following type:
age: number | undefinedThat is, the value of
agecan be either a number orundefined, or missing from the object entirely.
Example:
function printUser(user: User) {
console.log(user.age?.toFixed(1)); // safe: ?. checks whether age exists
}5. Optional fields in nested structures
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 absent6. 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:
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 interfaceToptional. This is often used for updates (updateUser(data)).
7. Optional fields and readonly
You can combine both modifiers:
interface Config {
readonly host?: string;
}Here the
hostproperty:
- 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:
function greet(name?: string) {
console.log(`Hi, ${name ?? "guest"}!`);
}
greet(); // Hi, guest!
greet("Tim"); // Hi, Tim!Here
namehas the typestring | undefined.
Summary
| What | How it is denoted | What it means |
|---|---|---|
| Optional property | age?: number | The property can be number or absent |
| Equivalent | `age: number | undefined` |
| Make all fields optional | Partial<Type> | Makes every property ? |
| Used in functions | param?: Type | The 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 readyA concise answer to help you respond confidently on this topic during an interview.