Sub topic 6
Object types with optional and readonly properties
This chapter assumes you know the primitive types (string, number, boolean), basic type annotations, and simple union types such as string | undefined. The examples assume "strict": true in your tsconfig.json, which enables strictNullChecks.
Describing an object's shape
An object type lists the names and types of an object's properties. You write it inline or give it a name with type:
type Point = { x: number; y: number };
const origin: Point = { x: 0, y: 0 };TypeScript checks that the object has every required property with the right type. It also rejects extra properties in an object literal:
const bad: Point = { x: 0, y: 0, z: 0 };
// Error: Object literal may only specify known properties, and 'z' does not exist in type 'Point'.Optional properties
A property followed by ? may be missing. Its type becomes T | undefined when you read it:
type User = {
name: string;
nickname?: string;
};
const ada: User = { name: "Ada" };
function greet(user: User): string {
if (user.nickname !== undefined) {
return `Hi, ${user.nickname}`;
}
return `Hi, ${user.name}`;
}Without the undefined check, user.nickname.toUpperCase() fails with "Object is possibly 'undefined'". The compiler forces you to handle the missing case.
Readonly properties
A readonly modifier stops assignment to a property after the object is created:
type Config = {
readonly host: string;
port: number;
};
const config: Config = { host: "localhost", port: 8080 };
config.port = 3000; // allowed
// config.host = "example.com";
// Error: Cannot assign to 'host' because it is a read-only property.readonly exists only at compile time. The emitted JavaScript contains no protection, so code that ignores the types can still change the value. readonly also applies one level deep:
type Settings = { readonly theme: { dark: boolean } };
const s: Settings = { theme: { dark: false } };
s.theme.dark = true; // allowed: only 'theme' is readonly, not 'theme.dark'To protect nested data, mark each nested object type as readonly too.
How object literals are inferred
When you omit the annotation, TypeScript infers the type from the literal:
const item = { id: 1, label: "draft" };
// inferred: { id: number; label: string }
item.label = "final"; // allowed, because inferred properties are mutableThe property label widens from the literal "draft" to string. Add as const when you want the literal and readonly types instead.
Common errors
- Reading an optional property without a check. Narrow it first, as shown in the
greetfunction above. - Assuming
readonlyfreezes the object at runtime. UseObject.freezefor that. It is also shallow, so nested objects stay mutable unless you freeze them too. - Adding unknown properties to an object literal. Excess property checks reject them. Add the property to the type, or assign the value to a variable first, which skips the check.
const frozen = Object.freeze({ host: "localhost" });
// frozen.host = "x"; // Error at compile time, and throws in strict-mode JavaScriptExercise
Exercise
Given type Account = { readonly id: number; email?: string; }, which of these lines compile? (a) account.id = 2; (b) account.email = "[email protected]"; (c) const e: string = account.email;
Show answer
(a) fails because id is readonly. (b) compiles because email is optional and writable. (c) fails with "Type 'string | undefined' is not assignable to type 'string'", so you need a check such as if (account.email !== undefined) first.