Lesson 36 of 50TypeScript
Interfaces and Type Aliases
Describe object shapes with optional and readonly props, readonly arrays and Record, avoid intersection and merging traps, and pick interface or type.
Almost all real data is objects: users, orders, API responses, props for a React component. Describing those shapes precisely is most of your day-to-day TypeScript, and "interface or type?" is a question you will be asked in code review and in interviews.
Object types
You describe an object by listing its properties and their types. You can write the shape inline, or give it a name with a type alias (type) or an interface.
// Inline
function greet(user: { name: string; age: number }) { /* ... */ }
// Type alias
type User = { name: string; age: number };
// Interface
interface Product {
id: string;
title: string;
priceCents: number;
}For a plain object shape, type User = {...} and interface User {...} behave almost identically. Names are PascalCase by convention. Properties are separated by ; or , (both work; most formatters use ;).
const book: Product = { id: "p1", title: "Dune" };
// Error: Property 'priceCents' is missing in type '{ id: string; title: string; }' but required in type 'Product'.Optional and readonly properties
A ? after the name makes a property optional: it may be missing. Its type becomes T | undefined, so you have to check it before use.
A readonly modifier stops reassignment after creation. It is a compile-time rule only (nothing is frozen at runtime), but it catches accidental mutation.
interface User {
readonly id: number;
email: string;
nickname?: string;
}
const user: User = { id: 1, email: "ada@example.com" };
user.id = 2;
// Error: Cannot assign to 'id' because it is a read-only property.
user.nickname.toUpperCase();
// Error: 'user.nickname' is possibly 'undefined'.
user.nickname?.toUpperCase(); // OKPress Run (⌘ Enter) to see what happens.label, what is the type of user.nickname?Index signatures and Record
Sometimes you do not know the keys ahead of time: a cache keyed by user id, a word count, translations. An index signature says "any string key, values of this type".
interface WordCounts {
[word: string]: number;
}
const counts: WordCounts = {};
counts["hello"] = 1;
counts.world = 2;The built-in Record<K, V> says the same thing more briefly, and it also works with a union of literal keys, where it requires every key.
type Prices = Record<string, number>; // any string key
type Role = "admin" | "editor" | "viewer";
const limits: Record<Role, number> = { admin: 100, editor: 50 };
// Error: Property 'viewer' is missing in type '{ admin: number; editor: number; }'.Record<Role, number> is great for lookup tables: add a fourth role to the union and every table that forgot it turns red.
interface vs type
Both name an object shape. The differences are small but real:
interface | type | |
|---|---|---|
| Object shapes | Yes | Yes |
| Unions, tuples, primitives | No | Yes (type Id = string | number) |
| Extending | extends keyword | Intersection & |
| Declaration merging | Yes | No (duplicate name is an error) |
| Error messages | Shows the name | May show the expanded shape |
Extending. An interface uses extends. A type alias combines shapes with an intersection (A & B, "has everything from both").
interface Animal { name: string }
interface Dog extends Animal { breed: string }
type Base = { id: number; createdAt: string };
type Post = Base & { title: string; body: string };Put fields every record shares in one base shape.
Declaration merging. Two interfaces with the same name in the same scope are merged into one. That is how libraries let you add fields to their types, for example adding a user property to Express's Request. With type, a second declaration is an error.
interface Window { appVersion: string }
// merges with the built-in Window type, so window.appVersion is now knownA common team rule: use interface for object shapes that others might extend, and type for everything else (unions, tuples, function types, mapped types). Many teams simply pick type everywhere for consistency. Either is fine; mixing randomly is not.
type, not interface?Structural compatibility and excess property checks
Remember structural typing: a value fits a type if it has at least the required properties. Extra properties are fine.
Press Run (⌘ Enter) to see what happens.There is one exception. When you pass an object literal directly, TypeScript runs an excess property check, because an unknown property in a fresh literal is almost always a typo.
hello({ name: "Sam", role: "admin" });
// Error: Object literal may only specify known properties, and 'role' does not exist in type 'Named'.
interface Options { timeout?: number; retries?: number }
const opts: Options = { timout: 500 };
// Error: Object literal may only specify known properties, but 'timout' does not exist in type 'Options'. Did you mean to write 'timeout'?Without that check, the typo timout would be silently ignored (both properties are optional), and you would never know why your timeout was not applied.
interface Point { x: number; y: number }
function plot(p: Point) {}
const a = { x: 1, y: 2, z: 3 };readonly arrays and ReadonlyArray
A readonly property stops you reassigning the property. It does nothing about the contents. This compiles, and mutates shared state:
type Cart = { readonly items: string[] };
const cart: Cart = { items: [] };
cart.items = []; // Error: Cannot assign to 'items' because it is a read-only property.
cart.items.push("book"); // fine: the array itself is mutableFor arrays there is a separate tool. readonly string[] (or the longer ReadonlyArray<string>, which is the same type) is an array type with every mutating method removed: no push, pop, splice, sort, reverse, and no index assignment. The non-mutating methods (map, filter, slice, toSorted) are all there.
Press Run (⌘ Enter) to see what happens.The assignability rule is one-way, and it is the reason to care:
- A mutable array can be passed where a readonly one is expected.
topScores(scores, 3)works with a plainnumber[]. - A readonly array cannot be passed where a mutable one is expected: "The type 'readonly string[]' is 'readonly' and cannot be assigned to the mutable type 'string[]'."
So the habit that pays off is: type array parameters as readonly T[] whenever the function does not mutate them. Callers can then pass either kind, including as const tuples and arrays from frozen state. A function that takes string[] forces every caller holding a readonly array to copy it or cast.
Two gotchas. First, as const arrays are readonly tuples of literals, so LEVELS.includes(input) with input: string is an error, because includes only accepts the literal members. Write a type guard that widens once: (LEVELS as readonly string[]).includes(input). Second, all of this is compile-time only. readonly does not freeze anything, and a cast gets straight past it. If you need runtime immutability, use Object.freeze (which is also shallow).
Intersections that collapse to never
An intersection A & B means "has everything from both". When both sides declare the same property with incompatible types, TypeScript does not report an error at the declaration. It intersects the property types instead:
type Base = { id: string; createdAt: string };
type Post = Base & { id: number; title: string };
// id is string & number, which is never
const p: Post = { id: 1, createdAt: "2026-10-22", title: "Hello" };
// Error: Type 'number' is not assignable to type 'never'.The error appears where you use the type, often in another file, and it talks about never rather than the real cause. With an interface, the same mistake is caught at the declaration, with a message that says what is wrong:
interface BaseI { id: string; createdAt: string }
interface PostI extends BaseI { id: number; title: string }
// Error: Interface 'PostI' incorrectly extends interface 'BaseI'.
// Types of property 'id' are incompatible.
// Type 'number' is not assignable to type 'string'.It gets stranger with discriminated unions. If the conflicting property is a literal discriminant, the whole type becomes never, not just the property:
type Click = { type: "click"; x: number };
type Key = { type: "key"; key: string };
type Both = Click & Key; // never: nothing can have type "click" and "key" at onceThis usually happens by accident, when someone writes & meaning "either" (that is |), or when a helper intersects a union member with a type that has a different type. If a type unexpectedly shows as never on hover, look for an intersection of conflicting literals.
Declaration merging, and how it bites
You saw that two interfaces with the same name merge. The rules are worth knowing precisely, because merging also happens when you did not ask for it:
- Properties from each declaration are combined. A property declared in both must have the same type, or you get "Subsequent property declarations must have the same type."
- Methods with the same name become overloads, later declarations first.
- It works across files for globals and for modules you augment, which is how
Window,process.envand Express'sRequestget extra fields. The details are in Declaration files and module augmentation.
The accidental case is a file with no import or export. TypeScript treats such a file as a global script, so its declarations live in the same scope as the DOM types. Write this in one:
interface Comment {
id: string;
body: string;
}
const c: Comment = { id: "c1", body: "Nice post" };
// Error: Type '{ id: string; body: string; }' is missing the following properties from type 'Comment':
// data, length, ownerDocument, appendData, and 59 more.Your Comment merged with the DOM's Comment node type. The same happens with Event, Request, Response, Image, Node and other common names. The fix is to make the file a module: any import or export (even export {}) gives it its own scope. Most real files already have one, which is why this surprises people in scratch files and small scripts. type aliases never merge, so type Comment = {...} in that file would report a duplicate name instead of silently changing meaning.
Team conventions: one rule and why
Earlier you saw the common split: interface for object shapes, type for everything else. Whichever way your team goes, the value is in having one rule and letting a tool enforce it, so code review stops debating it. typescript-eslint's consistent-type-definitions rule does exactly that. It defaults to "interface" and can be set to "type".
If you get to choose, a reasonable default with reasons you can defend:
- Object shapes:
interface. Conflicts are reported where they are written (as above), errors show the interface name instead of an expanded shape, andextendsrelationships are cached by the compiler. The TypeScript team's own performance guidance prefers interfaces over intersections for composing object types. - Everything else:
type. Unions, tuples, function types, mapped and conditional types cannot be interfaces anyway. - Merging: on purpose only. Use it to augment library or global types, in a
.d.tsfile named for what it augments. Never rely on two of your own interfaces with one name merging across your codebase.
Teams that pick "type everywhere" are not wrong. They trade those benefits for one keyword and no accidental merging. What costs real time is mixing both at random, so that every new contributor has to guess.
function total(xs: number[]) and a caller has const prices = [3, 5] as const. What is the best fix for the error at total(prices)?{ kind: "a"; n: number } & { kind: "b"; s: string }?What does this print?
const tags: readonly string[] = ["a", "b"];
(tags as string[]).push("c");
console.log(tags.length);Match the need to the tool.
Display name with optional fields
Given this interface:
interface User {
readonly id: number;
firstName: string;
lastName?: string;
nickname?: string;
}Write displayName(user: User): string:
- If
nicknameis present and not an empty string, return it. - Otherwise return
firstName, followed by a space andlastNameif there is one.
{ id: 1, firstName: "Ada", lastName: "Byron" } → "Ada Byron"
{ id: 2, firstName: "Sam", nickname: "Sammy" } → "Sammy"
{ id: 3, firstName: "Priya" } → "Priya"Count users by role
Write countByRole(users: Member[]): Record<Role, number> using these types:
type Role = "admin" | "editor" | "viewer";
type Member = { name: string; role: Role };The result must always have all three keys, even when a count is zero. That is exactly what Record<Role, number> promises.
[{ name: "Ada", role: "admin" }, { name: "Sam", role: "viewer" }, { name: "Leo", role: "viewer" }]
→ { admin: 1, editor: 0, viewer: 2 }- type alias
- A name for any type, written
type Name = .... Can describe objects, unions, tuples and more. - interface
- A named object shape. Supports
extendsand declaration merging. - optional property
- A property marked with
?that may be missing. Its type includesundefined. - Record<K, V>
- An object type whose keys are
Kand values areV. With a union of keys, every key is required. - excess property check
- An error when a fresh object literal has properties the target type does not declare. Catches typos.
- intersection
A & B: a type that has every property of bothAandB.- ReadonlyArray<T>
- An array type without mutating methods, also written
readonly T[]. Mutable arrays are assignable to it, not the other way round. - declaration merging
- Same-named interfaces (and some other declarations) in one scope combining into one type. Useful for augmentation, surprising by accident.