Sub topic 2
Declaring Object Shapes with Interfaces
Assume you know basic TypeScript annotations and are comfortable with JavaScript objects and functions. This chapter focuses on interfaces, which describe the properties and methods an object must provide.
An interface is a named contract for an object shape. A shape describes the members a value has, including their names and types.
interface User {
readonly id: number;
name: string;
email?: string;
}
function greet(user: User): string {
const email = user.email ?? "no email";
return `${user.name} (${email})`;
}
const user: User = {
id: 1,
name: "Ada",
};
user.name = "Ada Lovelace";
console.log(greet(user));
// user.id = 2;
// Error: Cannot assign to 'id' because it is a read-only property.The id and name properties are required. The email property is optional because its name ends with ?. An optional property may be absent, so code that reads it must handle undefined.
The readonly modifier prevents assignment through that value after creation. It does not automatically freeze the object at runtime. JavaScript can still change the object through other code or through an unsafe cast.
Structural typing
TypeScript uses structural typing. A value matches an interface when it has all the required members with compatible types. The value does not need to explicitly declare that it implements the interface.
interface Point {
x: number;
y: number;
}
function length(point: Point): number {
return Math.sqrt(point.x ** 2 + point.y ** 2);
}
const origin3d = { x: 3, y: 4, z: 5 };
console.log(length(origin3d)); // 5origin3d has x and y, so it can be passed to length. Its extra z property does not prevent compatibility.
TypeScript applies a stricter check to a fresh object literal. This often catches misspelled property names:
// length({ x: 3, y: 4, z: 5 });
// Error: Object literal may only specify known properties.Assigning the object to a variable first allows the extra property because the variable already has a compatible shape.
| Declaration | Meaning |
|---|---|
| `name: string` | Required string property |
| `email?: string` | Optional string property |
| `readonly id: number` | Property cannot be reassigned through this value |
| `save(): void` | Required method |
Visualizing an interface check
A common error is confusing optional with nullable. An optional property may be missing. A nullable property is present but may contain null. If both are allowed, write the intent explicitly, such as email?: string | null.
Use interfaces when you want to name and document an object contract. Keep required data required, mark genuinely optional data with ?, and use readonly when callers should not replace a property.
Exercise
Why can a variable with { x: number; y: number; z: number } be passed to a function expecting Point, while a fresh object literal with the same three properties may produce an error?
Show answer
Structural typing allows a variable with at least the required members. Fresh object literals receive an excess-property check, which reports properties that are not listed in the target interface.