Sub topic 2
Declaring object shapes with interfaces
An interface is a named description of the shape of an object. It lists the properties a value must have and the type of each one. This chapter covers interface syntax, how the compiler checks values against it, and the errors you are most likely to meet.
This chapter assumes you know basic type annotations (string, number, boolean, arrays), plain JavaScript objects, functions, and classes, and that you can run tsc or use an editor that shows type errors. It does not repeat structural typing in detail. Optional and readonly properties, extends, declaration merging, and the choice between interface and type each get their own chapter, so this one only touches them.
What an interface declares
An interface declaration uses the interface keyword, a name, and a block of members. By convention the name starts with a capital letter.
interface User {
readonly id: number;
name: string;
email?: string;
}
const user: User = { id: 1, name: "Ada" };
user.name = "Ada Lovelace"; // allowed
// user.id = 2; // error: Cannot assign to 'id' because it is a read-only property.The User interface has three members:
idis required and cannot be reassigned after the object is created, because ofreadonly.nameis required and can be reassigned.emailis optional, because of the?. AUsermay omit it.
An interface exists only at compile time. It produces no JavaScript, so you cannot test for an interface at runtime with instanceof, and you cannot inspect it from running code. After compilation, user is an ordinary object.
Members you can declare
Besides plain properties, an interface can contain methods, call signatures, and index signatures. A method can be written in two styles:
interface Counter {
count: number;
increment(by: number): void; // method style
reset: () => void; // property style
}
const counter: Counter = {
count: 0,
increment(by) {
this.count += by;
},
reset() {
this.count = 0;
},
};
counter.increment(2);
console.log(counter.count); // 2Both styles describe a callable member. They differ in how strictly the compiler compares parameter types when strictFunctionTypes is on: property style is checked strictly, and method style is checked more loosely. For most code this does not matter, but prefer property style when you want the stricter check.
Separate members with ; or ,, or with a line break. Most projects use semicolons.
How the compiler checks a value
TypeScript compares shapes, not names. A value matches an interface when it has every required member, and each member has a compatible type. The value does not need to say that it implements the interface.
interface Point {
x: number;
y: number;
}
function length(p: Point): number {
return Math.sqrt(p.x * p.x + p.y * p.y);
}
const origin3d = { x: 3, y: 4, z: 5 };
console.log(length(origin3d)); // 5, because origin3d has every property Point requiresorigin3d has an extra property z. That is fine here, because the check only asks whether x and y are present with the right types.
Excess property checks on object literals
There is one exception that surprises many people. When you write an object literal directly where an interface is expected, the compiler also rejects properties the interface does not list. This is called an excess property check. It catches typos.
interface Point {
x: number;
y: number;
}
// error: Object literal may only specify known properties, and 'z' does not exist in type 'Point'.
// const p: Point = { x: 1, y: 2, z: 3 };
const withZ = { x: 1, y: 2, z: 3 };
const p: Point = withZ; // allowed: withZ is not a fresh object literal
console.log(p.x);The check applies only to a fresh literal, meaning an object literal written at the point of assignment or call. Once the value sits in a variable, the extra property no longer triggers an error. The extra property is still there at runtime, but you cannot read p.z through the Point type.
Weak types
An interface whose members are all optional is a weak type. TypeScript refuses to assign a value to a weak type if the value shares no properties with it.
interface Options {
verbose?: boolean;
retries?: number;
}
const flags = { colour: true };
// const opts: Options = flags; // error: Type '{ colour: boolean; }' has no properties in common with type 'Options'.
const opts: Options = { retries: 3 };
console.log(opts.retries); // 3Without this rule, any object would match an all-optional interface, and a misspelled option would go unnoticed.
Interfaces in practice
Nesting and arrays
Members can have any type, including other interfaces and arrays of them.
interface Address {
city: string;
country: string;
}
interface Customer {
name: string;
addresses: Address[];
primary?: Address;
}
const customer: Customer = {
name: "Linus",
addresses: [{ city: "Helsinki", country: "Finland" }],
};
console.log(customer.addresses[0].city); // HelsinkiReading an optional member gives you T | undefined, so you must check it before use. With strictNullChecks on, this does not compile:
interface Address {
city: string;
}
interface Customer {
primary?: Address;
}
function primaryCity(c: Customer): string {
// return c.primary.city; // error: 'c.primary' is possibly 'undefined'.
return c.primary?.city ?? "unknown";
}
console.log(primaryCity({})); // unknownThe optional chaining operator ?. and the nullish coalescing operator ?? are the usual way to handle this.
Interfaces for function parameters
Interfaces are most useful at boundaries, such as function parameters and return values. They document what the caller must supply.
interface CreateUserInput {
name: string;
email?: string;
}
interface UserRecord {
readonly id: number;
name: string;
email: string;
}
let nextId = 1;
function createUser(input: CreateUserInput): UserRecord {
return {
id: nextId++,
name: input.name,
email: input.email ?? "[email protected]",
};
}
console.log(createUser({ name: "Grace" }));Keeping the input and the stored record as separate interfaces lets each one change for its own reasons.
Implementing and extending
A class can promise to match an interface with implements, and the compiler then checks every member.
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string): void {
console.log(message);
}
}
const logger: Logger = new ConsoleLogger();
logger.log("started");An interface can also build on another with extends.
interface Named {
name: string;
}
interface Employee extends Named {
employeeId: number;
}
const e: Employee = { name: "Grace", employeeId: 7 };
console.log(e.employeeId);Later chapters treat both in full.
Common errors and how to read them
The same few messages cover most mistakes with interfaces.
| Message (shortened) | Cause | Fix |
|---|---|---|
| Property 'x' is missing in type ... but required in type ... | A required member is absent | Add the member, or make it optional with `?` |
| Object literal may only specify known properties | Excess property check on a fresh literal | Remove the typo, add the member to the interface, or assign through a variable if the extra data is intended |
| Type 'string' is not assignable to type 'number' | A member has the wrong type | Correct the value or the declared type |
| Cannot assign to 'id' because it is a read-only property | Writing to a `readonly` member | Create a new object instead of mutating |
| 'x' is possibly 'undefined' | Reading an optional member without a check | Use `?.`, `??`, or an `if` guard |
When a message is long, read the last lines first. TypeScript prints the deepest mismatch there, which usually names the exact property at fault.
Two gotchas
readonly is a compile-time rule only. It does not freeze the object at runtime, and a value typed through a different, non-readonly interface can still be changed.
interface ReadonlyPoint {
readonly x: number;
}
interface MutablePoint {
x: number;
}
const fixed: ReadonlyPoint = { x: 1 };
const loose: MutablePoint = fixed; // allowed
loose.x = 99;
console.log(fixed.x); // 99Also, an interface does not validate data that arrives at runtime. If you parse JSON and annotate the result as User, the compiler trusts you. A wrong payload will not be caught by the interface, so validate external input with a runtime check.
How interfaces relate to the rest of the plan
Interfaces describe object shapes, and so do type aliases. The next chapter introduces type aliases, and the final chapter gives criteria for choosing between them. The diagram shows the checks you have just seen.
Exercise
Given interface Point { x: number; y: number }, why does const a = { x: 1, y: 2, z: 3 }; const p: Point = a; compile, while const p: Point = { x: 1, y: 2, z: 3 }; does not?
Show answer
Assignment checks only that the value has every required member of Point with a compatible type, and a does. The second statement uses a fresh object literal, so the compiler also applies the excess property check and rejects the unknown property z. Passing the value through a variable removes the freshness, so the check no longer applies.
Exercise
You declare interface Options { verbose?: boolean; retries?: number } and write const o: Options = { verbos: true };. What happens, and why?
Show answer
The compiler reports an error. The literal is fresh, so verbos is flagged as an unknown property by the excess property check. Even if the value came from a variable, Options is a weak type, so assigning a value that shares no properties with it would also be rejected.
Exercise
A function returns JSON.parse(text) as User. The text is {"id": "abc"}. Does the compiler report an error, and does the interface protect you at runtime?
Show answer
No error is reported, because as User tells the compiler to trust you. The interface is erased during compilation, so nothing checks the data at runtime, and id will be a string even though User declares a number. Validate the parsed value with a runtime check before using it.