Sub topic 7
Describe objects with interfaces and type aliases
This chapter assumes you have a working tsconfig.json, have renamed at least one .js file to .ts, and can read basic compiler errors. After renaming, the compiler usually reports errors like Property 'name' does not exist on type '{}' or Parameter 'user' implicitly has an 'any' type. Most of them come from objects whose shape the compiler cannot see. Interfaces and type aliases name those shapes.
Why object shapes come first
JavaScript code passes plain objects around. A function takes user, reads user.name, and trusts that the caller built the object correctly. TypeScript checks objects by structure, not by name. If an object has the properties a type requires, it fits that type. This is called structural typing.
That fits a JavaScript migration well. You rarely need to change how objects are created. You only describe what they already look like, then the compiler checks every use.
Interfaces
An interface declares the properties an object must have. Here is the function from the // @ts-check example, after conversion.
interface User {
name: string;
age: number;
email?: string;
}
function formatUser(user: User): string {
return user.name.toUpperCase() + " (" + user.age + ")";
}
console.log(formatUser({ name: "Ada", age: 36 }));The ? after email marks an optional property. Its type is string | undefined. Code that reads user.email must handle the missing case, which later chapters cover under null safety.
You can also mark properties readonly and describe methods.
interface Account {
readonly id: string;
owner: string;
balance: number;
deposit(amount: number): void;
}
const account: Account = {
id: "acc-1",
owner: "Ada",
balance: 0,
deposit(amount) {
this.balance += amount;
},
};
account.deposit(50);
console.log(account.balance);
// account.id = "acc-2"; // Error: Cannot assign to 'id' because it is a read-only property.readonly is checked only at compile time. It does not freeze the object at runtime.
Type aliases
A type alias gives a name to any type. For object shapes it looks almost the same as an interface.
type Point = {
x: number;
y: number;
};
type Id = string | number;
type Status = "active" | "suspended" | "closed";
const origin: Point = { x: 0, y: 0 };
const id: Id = "u-42";
const status: Status = "active";
console.log(origin, id, status);Aliases can name unions, string literal types, tuples and function types. Interfaces cannot name a union.
Interface or type alias
For plain object shapes, either works. The differences matter in a few cases.
| Feature | `interface` | `type` |
|---|---|---|
| Object shapes | Yes | Yes |
| Unions and literal types | No | Yes |
| Extending another type | `extends` | Intersection with `&` |
| Declaration merging (same name declared twice) | Yes | No, duplicate name is an error |
| Can be implemented by a class | Yes | Yes, if it is an object type |
A practical rule for a migration: use interface for object shapes that describe your domain (User, Order), and type for unions, literals and anything computed from other types. Pick one style for plain objects and keep it consistent across the codebase.
Extending shapes
Real data often builds on a smaller shape. With interfaces, use extends.
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: string;
}
const worker: Employee = { name: "Grace", age: 45, employeeId: "e-7" };
console.log(worker.name, worker.employeeId);With aliases, combine types using an intersection.
type Person = { name: string; age: number };
type Employee = Person & { employeeId: string };
const worker: Employee = { name: "Grace", age: 45, employeeId: "e-7" };
console.log(worker);If two members of an extends chain conflict, such as age: number and age: string, the compiler reports an error. With &, the conflicting property becomes never, and you find out only when you try to assign a value. This is one reason to prefer extends for shapes that grow by inheritance.
Nested objects and arrays
JavaScript objects often hold other objects. Name each level so errors point at the right place.
interface Address {
street: string;
city: string;
}
interface Customer {
id: number;
name: string;
address: Address;
tags: string[];
}
const customer: Customer = {
id: 1,
name: "Ada",
address: { street: "1 Main St", city: "London" },
tags: ["vip"],
};
console.log(customer.address.city);Inline types such as address: { street: string; city: string } work too. A named interface is better once you use the shape in two places.
Dictionaries and index signatures
Some JavaScript objects are used as maps, with keys decided at runtime. An index signature describes them.
interface Scores {
[player: string]: number;
}
const scores: Scores = { ada: 10, grace: 12 };
scores["linus"] = 8;
console.log(scores.ada);The Record<string, number> utility type means the same thing and is shorter. Be aware that with an index signature, scores.unknownName has type number, not number | undefined, unless you enable noUncheckedIndexedAccess. That option is worth adding when you turn on strict checking.
Excess property checks
When you assign an object literal directly to a typed variable, the compiler rejects properties that the type does not list.
interface User {
name: string;
age: number;
}
// Error: Object literal may only specify known properties,
// and 'nmae' does not exist in type 'User'.
const user: User = { nmae: "Ada", age: 36 };This catches typos. The check applies only to fresh object literals. If you first assign the object to a variable and then pass the variable, extra properties are allowed, because structural typing only requires the listed properties to be present.
Deriving shapes from existing values
During a migration you may have large object constants. You do not have to write the interface by hand first. The typeof operator in a type position copies the shape of a value.
const defaults = {
retries: 3,
verbose: false,
host: "localhost",
};
type Settings = typeof defaults;
function connect(options: Settings): string {
return options.host + " x" + options.retries;
}
console.log(connect(defaults));Use this to get unblocked quickly. Later, replace it with an explicit interface when the shape is part of a public contract, because inferred types follow every edit to the value, including accidental ones.
Choosing a shape for legacy functions
A common migration problem is a function that accepts an "options" object whose fields are all optional.
interface FetchOptions {
timeoutMs?: number;
retries?: number;
headers?: Record<string, string>;
}
function fetchData(url: string, options: FetchOptions = {}): string {
const timeout = options.timeoutMs ?? 5000;
const retries = options.retries ?? 0;
return `${url} timeout=${timeout} retries=${retries}`;
}
console.log(fetchData("/api/users"));
console.log(fetchData("/api/users", { retries: 2 }));The default = {} and the ?? operator handle the missing values. If every property of an interface is optional, TypeScript also warns when you pass something that shares no properties with it, which catches calls with the wrong kind of argument.
Where to put the types
Keep interfaces next to the code that owns them while the migration is small. When several files share a shape, move it to a types.ts file and export it.
// types.ts
export interface User {
name: string;
age: number;
}// format.ts
import type { User } from "./types";
export function formatUser(user: User): string {
return `${user.name} (${user.age})`;
}import type is erased at compile time, so it never creates a runtime require for a file that contains only types.
Common errors
- Casting instead of describing. Writing
{} as Usersilences the compiler but leaves the object empty. Build a real value or make the properties optional. - Making everything optional. Marking every property with
?removes most of the checking. Mark a property optional only when real data can omit it. - Using
Objector{}as a type. Both accept almost any value. Use a named shape, orRecord<string, unknown>for "some object". - Using
anyfor unknown fields. Useunknownor a precise type, covered in a later chapter. - Duplicate interface names by accident. Two interfaces with the same name in the same scope merge silently. A shape you did not mean to extend can gain fields.
Exercise
A legacy function reads order.customer.email and order.items.length, where email may be absent. Write the interfaces Customer and Order, and explain why { id: 1, items: [], customer: { name: "Ada" }, total: 5 } fails when assigned directly to an Order variable if Order has no total property.
Show answer
interface Customer { name: string; email?: string } and interface Order { id: number; customer: Customer; items: string[] }. The literal fails because of the excess property check: when a fresh object literal is assigned to a typed variable, any property not in the type (here total) is an error. Assigning the literal to an untyped variable first, then passing that variable, would not trigger the check.
Exercise
Why is type Employee = Person & { age: string } risky when Person already has age: number, and what would you use instead?
Show answer
The intersection makes age the type never (number and string cannot both hold), so no value can satisfy it and the problem shows up late, at assignment. With interface Employee extends Person, the compiler reports the conflict immediately at the declaration. Use extends for shapes built by inheritance, or give the property a different name.