Sub topic 6
Object types with optional and readonly properties
This chapter assumes you know the primitive types (string, number, boolean), how type annotations and inference work, and that strictNullChecks is on. Everything below assumes "strict": true in tsconfig.json, which is the default for new projects created with tsc --init.
Describing the shape of an object
An object type lists the property names an object must have and the type of each one. TypeScript checks objects by shape, not by name. Any value with the right properties of the right types matches.
type User = {
readonly id: number;
name: string;
email?: string;
};
const user: User = { id: 1, name: "Ada" };
user.name = "Grace"; // ok: name is mutable
// user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property.
// user.age; // Error: Property 'age' does not exist on type 'User'.You can write the same shape inline, as in function show(u: { name: string }) {}. A named type alias is easier to reuse and read once the shape has more than two or three properties. An interface declares object shapes in a similar way, and a later chapter compares the two.
Separate the members with ; or ,. Both are valid, and most style guides pick ;.
Optional properties
A ? after a property name makes the property optional. Objects may leave it out.
Reading an optional property gives you string | undefined, not string. The compiler makes you handle the missing case before you use the value.
type User = {
readonly id: number;
name: string;
email?: string;
};
function describeContact(user: User): string {
if (user.email === undefined) {
return `${user.name} (no email)`;
}
return `${user.name} <${user.email.toLowerCase()}>`;
}
function emailDomain(user: User): string {
// Optional chaining gives undefined when email is missing.
// ?? supplies a fallback for that case.
return user.email?.split("@")[1] ?? "unknown";
}
console.log(describeContact({ id: 1, name: "Ada" }));
console.log(emailDomain({ id: 2, name: "Grace", email: "[email protected]" }));Checking user.email === undefined narrows the property inside each branch, as with any union.
Optional is not the same as `| undefined`
These two declarations look similar but behave differently:
type A = { email?: string }; // key may be absent
type B = { email: string | undefined }; // key must be present
const a: A = {}; // ok
// const b: B = {}; // Error: Property 'email' is missing in type '{}' but required in type 'B'.
const b: B = { email: undefined }; // okUse ? when callers may omit the key. Use T | undefined when the key is always present and the value may be unset.
The exactOptionalPropertyTypes compiler option is not part of strict. With it on, email?: string rejects an explicit email: undefined, so "absent" and "present but undefined" become distinct states. Leave it off unless you need that distinction.
Readonly properties
A readonly modifier stops code from assigning to a property after the object is created. It is a compile-time check only. The emitted JavaScript contains no protection, and Object.freeze is what actually freezes an object at runtime.
Three limits catch people out.
- It is shallow.
readonlyapplies to the property itself, not to what the property refers to. - It does not affect assignability. The compiler lets you assign a readonly-property object to a type with mutable properties.
- It only blocks assignment. It does not make an array or nested object immutable.
type Team = { readonly members: string[] };
const team: Team = { members: ["Ada"] };
team.members.push("Grace"); // allowed: the array itself is mutable
// team.members = []; // Error: Cannot assign to 'members' because it is a read-only property.
type Frozen = { readonly members: readonly string[] };
const frozen: Frozen = { members: ["Ada"] };
// frozen.members.push("Grace"); // Error: Property 'push' does not exist on type 'readonly string[]'.
const locked: { readonly count: number } = { count: 1 };
const loose: { count: number } = locked; // allowed, no error
loose.count = 99; // changes the same object
console.log(locked.count); // 99If you need depth, apply readonly at each level, or use readonly string[] for arrays as in the Frozen type above.
Excess property checks
When you write an object literal directly where a type is expected, TypeScript rejects properties the type does not list. This check catches typos in option names.
type User = { readonly id: number; name: string; email?: string };
// const u: User = { id: 1, name: "Ada", emial: "[email protected]" };
// Error: Object literal may only specify known properties, and 'emial' does not exist in type 'User'.
const extra = { id: 2, name: "Bob", nickname: "B" };
const bob: User = extra; // ok: not a fresh literal, so no excess checkThe check applies only to fresh literals. Once an object has been stored in a variable, extra properties are allowed because a type describes the minimum shape a value must have. A value with more properties still satisfies it.
A related rule applies to types where every property is optional. TypeScript requires at least one matching property, so const o: { a?: number } = { b: 1 } is an error even through a variable. This is called weak type detection.
How the compiler infers object literals
Without an annotation, TypeScript infers an object type from the literal. It widens each property type, even inside a const declaration.
const settings = { retries: 3, mode: "fast" };
// inferred: { retries: number; mode: string }
settings.mode = "slow"; // ok: const stops reassignment of settings, not of its properties
// settings.mode = 42; // Error: Type 'number' is not assignable to type 'string'.
// settings.timeout = 10; // Error: Property 'timeout' does not exist on type '{ retries: number; mode: string; }'.Inference never produces optional or readonly properties on its own. If you want them, annotate the variable. If you want narrower literal types such as "fast", a later chapter covers as const and satisfies.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `'x' is possibly 'undefined'` | Reading an optional property without a check | Narrow with `if`, use `?.`, or provide a default with `??` |
| `Cannot assign to 'id' because it is a read-only property` | Assigning to a `readonly` property | Build a new object, for example `{ ...user, id: 2 }`, or remove `readonly` if mutation is intended |
| `Object literal may only specify known properties` | Typo or extra key in a literal | Fix the name, or add the property to the type |
| Mutation of a `readonly` array property compiles | `readonly` is shallow | Type the array as `readonly T[]` |
| `Property 'x' is missing in type` | Required key omitted | Add the key, or make it optional with `?` |
Putting it together
This function applies defaults to a type with optional properties and returns a new object, so it never mutates its input.
type Options = {
readonly url: string;
timeoutMs?: number;
retries?: number;
};
type ResolvedOptions = {
readonly url: string;
readonly timeoutMs: number;
readonly retries: number;
};
function resolve(options: Options): ResolvedOptions {
return {
url: options.url,
timeoutMs: options.timeoutMs ?? 5000,
retries: options.retries ?? 3,
};
}
const resolved = resolve({ url: "https://example.com", retries: 0 });
console.log(resolved); // { url: 'https://example.com', timeoutMs: 5000, retries: 0 }The code uses ?? rather than ||. With ||, an explicit retries: 0 would be replaced by 3 because 0 is falsy.
Exercise
Given type Config = { readonly tags: string[]; label?: string } and const c: Config = { tags: ["a"] }, which of these lines produce a compile error, and why? (1) c.tags.push("b"); (2) c.tags = []; (3) c.label.toUpperCase();
Show answer
Lines 2 and 3 are errors. Line 1 compiles because readonly is shallow: it blocks reassigning tags but not mutating the array it refers to. Line 2 assigns to a read-only property. Line 3 reads label, whose type is string | undefined, so calling a method on it without narrowing is an error ("'c.label' is possibly 'undefined'"). To make line 1 an error too, declare tags as readonly string[].
Exercise
Why does const a: { n?: number } = { n: 1, m: 2 } fail, while const src = { n: 1, m: 2 }; const b: { n?: number } = src; succeeds?
Show answer
The first assigns a fresh object literal, so excess property checking rejects the unknown property m. The second assigns a variable, which is not a fresh literal, so only the shape is checked. src has an n of type number, so it matches { n?: number }, and the extra property m is allowed.