Sub topic 4
Generic Interfaces and Type Aliases
This chapter assumes you can write generic functions with a type parameter such as <T>. It also assumes you know basic interfaces, type aliases, and union types. Here you apply type parameters to type declarations, so one shape can describe many kinds of data.
Why types need parameters too
A generic function ties its parameter types to its return type. The same need appears when you describe data. Consider two interfaces that differ only in one field type:
interface NumberBox {
value: number;
}
interface StringBox {
value: string;
}Copying the declaration for every type does not scale. Using any or unknown for value makes the type of the contents unknown at each use. A generic interface declares the shape once and lets each use supply the type.
Declaring generic interfaces and aliases
Type parameters go in angle brackets after the name. Each use supplies concrete type arguments.
interface Box<T> {
value: T;
}
type Pair<A, B> = [A, B];
const numberBox: Box<number> = { value: 10 };
const entry: Pair<string, boolean> = ["active", true];Box<number> is a new type obtained by replacing every T in Box with number. Box on its own is not a type. It is a template that must be given arguments before you can use it as a type.
Mermaid diagrams must use the diagram fence below.
Generic interfaces that describe behavior
Interfaces can describe methods as well as fields. The type parameter then appears in method signatures, and every member that mentions it stays consistent.
interface User {
id: number;
name: string;
}
interface Repository<T> {
getById(id: number): T | undefined;
save(item: T): void;
all(): T[];
}
class InMemoryUserRepo implements Repository<User> {
private users = new Map<number, User>();
getById(id: number): User | undefined {
return this.users.get(id);
}
save(item: User): void {
this.users.set(item.id, item);
}
all(): User[] {
return [...this.users.values()];
}
}
const repo = new InMemoryUserRepo();
repo.save({ id: 1, name: "Ada" });
console.log(repo.getById(1)?.name); // Adaimplements Repository<User> fixes T to User. If save accepted a string, the compiler would report that the class does not satisfy the interface.
Generic methods inside a generic interface
An interface can have its own type parameter and also contain methods with their own. The two sets are independent. The method's parameter is chosen per call, while the interface's parameter is fixed when the type is used.
interface Container<T> {
value: T;
map<U>(fn: (value: T) => U): Container<U>;
}
function container<T>(value: T): Container<T> {
return {
value,
map: (fn) => container(fn(value)),
};
}
const length = container("hello").map((s) => s.length); // Container<number>
console.log(length.value); // 5Here T is string for the first container, and U is inferred as number from the callback's return type. The result is a Container<number>.
Generic type aliases
An alias can name any type, so a generic alias can stand for more than an object shape. Common uses are function types, unions, and tuples.
type Predicate<T> = (value: T) => boolean;
const isEven: Predicate<number> = (n) => n % 2 === 0;
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function parseNumber(input: string): Result<number, string> {
const n = Number(input);
return Number.isNaN(n)
? { ok: false, error: "not a number" }
: { ok: true, value: n };
}
const r = parseNumber("42");
if (r.ok) {
console.log(r.value.toFixed(1)); // 42.0
} else {
console.log(r.error);
}Result<T, E> is a union, so it can only be written as an alias. The ok field acts as a discriminant. After the if (r.ok) check, TypeScript narrows r to the success member, and r.value is a number.
Recursive generic aliases
A generic type can refer to itself with its own arguments. This describes nested data such as trees.
type Tree<T> = {
value: T;
children: Tree<T>[];
};
const tree: Tree<string> = {
value: "root",
children: [
{ value: "a", children: [] },
{ value: "b", children: [{ value: "c", children: [] }] },
],
};Every level of the tree holds the same T. Putting a number at any depth is a compile error.
Constraining type parameters in declarations
Type parameters on interfaces and aliases accept the same extends constraints as functions. A constraint limits which arguments are allowed, and it lets the declaration rely on those properties.
interface HasId {
id: number;
}
interface Entity<T extends HasId> {
data: T;
key: T["id"];
}
const ok: Entity<{ id: number; name: string }> = {
data: { id: 7, name: "Ada" },
key: 7,
};
// Entity<string> would be an error: string does not satisfy HasIdT["id"] is an indexed access type, covered in a later chapter. It means "the type of the id property of T".
Interface or alias?
For plain object shapes the two are nearly interchangeable. The differences matter at the edges.
| Feature | `interface` | `type` alias |
|---|---|---|
| Object shapes | Yes | Yes |
| Unions and tuples | No | Yes |
| Extending | `extends`, and classes can `implements` it | Intersection with `&` |
| Declaration merging | Yes | No |
| Mapped or conditional types | No | Yes |
When two interface declarations share a name, TypeScript merges them. For generic interfaces, every declaration must use identical type parameter names, constraints, and defaults. A mismatch is an error.
interface Queue<T> {
push(item: T): void;
}
interface Queue<T> {
pop(): T | undefined;
}
const q: Queue<number> = {
push(item) {
console.log("pushed", item);
},
pop() {
return undefined;
},
};
q.push(1);Use an interface for object contracts that classes implement or that other code may extend. Use an alias for unions, tuples, function types, and anything computed from other types.
Common errors
- Omitting required type arguments. A generic type used without arguments fails with a message such as
Generic type 'Box' requires 1 type argument(s). - Confusing the position of the parameter.
Box<string>[]is an array of boxes, whileBox<string[]>is one box holding an array. - Passing a type that violates the constraint.
Entity<string>fails becausestringhas noid. - Inconsistent merged declarations. Two
interface Queuedeclarations with different parameter names, such as<T>and<U>, do not merge. - Parameters that do nothing. A type parameter that no member uses adds noise.
interface Tag<T> { name: string }acceptsTag<number>andTag<string>interchangeably, because TypeScript compares structure and nothing connectsTto the members.
Practice
Exercise
Write a generic type alias Nullable<T> that allows either a T or null. Then declare const name: Nullable<string> and give it the value null.
Show answer
type Nullable<T> = T | null;
const name: Nullable<string> = null;
Nullable<string> expands to string | null, so both "Ada" and null are valid values.
Exercise
Why does const b: Box = { value: 1 }; fail when Box is declared as interface Box<T> { value: T }, and how do you fix it?
Show answer
Box is a generic template, and a variable annotation does not infer type arguments. The compiler reports that Box requires one type argument. Fix it by supplying the argument: const b: Box<number> = { value: 1 };.
Exercise
Given interface Repository<T> { getById(id: number): T | undefined; save(item: T): void; }, what type does getById return for Repository<User>, and what happens if a class declares implements Repository<User> but its save takes a string?
Show answer
getById returns User | undefined. The class fails to compile, because its save parameter type string is not compatible with User, so the class does not satisfy Repository<User>.