Sub topic 12
Generic interfaces and type aliases
This chapter assumes you can declare interfaces and type aliases, and that you know how unions, optional properties, and function types work. It also assumes you have seen a generic function such as function identity<T>(x: T): T. Here you apply the same idea to named types.
Why generic shapes
Suppose you need a wrapper that holds a value. Without generics you have two bad options. You can write one interface per value type (NumberBox, StringBox, and so on), or you can use any and lose type checking.
A generic declaration adds a type parameter. The declaration becomes a template, and each use supplies a concrete type. Interfaces and type aliases both support this.
interface Box<T> {
value: T;
}
type Pair<A, B> = [A, B];
const numberBox: Box<number> = { value: 42 };
const entry: Pair<string, number> = ["age", 30];Box<number> is the shape { value: number }. Pair<string, number> is the tuple [string, number]. The parameter names (T, A, B) are placeholders. Single capital letters are the convention, but descriptive names such as TValue or Item are fine when a declaration has several parameters.
Because TypeScript is structurally typed, Box<number> has no identity beyond its shape. Any object with a value: number property is assignable to it.
Type parameters are required unless defaulted
A generic type must be given all of its arguments wherever it is used as a type. This is different from generic functions, where TypeScript usually infers them.
interface Box<T> {
value: T;
}
// const b: Box = { value: 1 };
// error: Generic type 'Box<T>' requires 1 type argument(s).
const b: Box<number> = { value: 1 };
console.log(b.value);Annotations never infer their arguments. If you want a function to infer them, make the function generic and let the call site decide:
interface Box<T> {
value: T;
}
function box<T>(value: T): Box<T> {
return { value };
}
const s = box("hello"); // Box<string>
const n = box(7); // Box<number>
console.log(s.value.toUpperCase(), n.value.toFixed(1));Note that box("hello") infers T as string, not the literal "hello", because the result property is mutable. Inference of literal types depends on the context, which is covered later in this chapter.
Default type parameters
A type parameter can have a default, written with =. The default applies when the caller omits the argument.
interface ApiResponse<TData = unknown, TError = Error> {
data?: TData;
error?: TError;
status: number;
}
const raw: ApiResponse = { status: 200 };
const typed: ApiResponse<string[]> = { status: 200, data: ["a", "b"] };
const custom: ApiResponse<string[], { code: number }> = {
status: 500,
error: { code: 42 },
};
console.log(raw.status, typed.data, custom.error?.code);Rules for defaults:
- Parameters with defaults must come after parameters without defaults.
- A caller can omit trailing arguments but cannot skip one in the middle. To set
TErroryou must also writeTData. - Defaults are a good place to choose
unknownoverany, so that unspecified data stays safe to handle.
Constraints with extends
An unconstrained T can be anything, so you can do almost nothing with it inside the declaration. A constraint restricts what callers may pass, and in return lets the declaration rely on the constraint's members.
interface HasId {
id: number;
}
interface Repository<T extends HasId> {
getById(id: number): T | undefined;
save(item: T): void;
all(): T[];
}
interface User extends HasId {
name: string;
}
class MemoryUserRepo implements Repository<User> {
private items = new Map<number, User>();
getById(id: number): User | undefined {
return this.items.get(id);
}
save(item: User): void {
this.items.set(item.id, item);
}
all(): User[] {
return [...this.items.values()];
}
}
const repo = new MemoryUserRepo();
repo.save({ id: 1, name: "Ada" });
console.log(repo.getById(1)?.name);Repository<string> would be an error, since string has no id property. Here extends means "is assignable to", not class inheritance. Any type with a numeric id passes, including types that never mention HasId.
A constraint can refer to another parameter. The classic case is K extends keyof T:
type PropertyGetter<T, K extends keyof T> = (obj: T) => T[K];
interface Person {
name: string;
age: number;
}
const getAge: PropertyGetter<Person, "age"> = (p) => p.age;
console.log(getAge({ name: "Grace", age: 85 }));T[K] is an indexed access type. With K set to "age", it resolves to number.
Generic function types and call signatures
Where the type parameter is declared changes what the type means. Compare these two.
// The parameter belongs to the interface: choose T once, when you name the type.
interface MapperA<T> {
(input: T): T;
}
// The parameter belongs to the call: each call can pick its own T.
interface MapperB {
<T>(input: T): T;
}
const identity: MapperB = (x) => x;
const a = identity("text"); // string
const b = identity(10); // number
const onlyStrings: MapperA<string> = (x) => x.trim();
console.log(a, b, onlyStrings(" ok "));MapperA<string> accepts only strings forever. MapperB is a single value that works for any type at each call. The same distinction applies to type aliases:
type FnA<T> = (input: T) => T;
type FnB = <T>(input: T) => T;If you see an error such as "Type 'T' is not assignable to type 'T'" when assigning a function, check whether the parameter is declared on the type or on the call.
A generic alias that does real work
Aliases can take parameters and also compute with them, which interfaces cannot do. A conditional type chooses between two outcomes.
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
type ElementOf<T> = T extends (infer U)[] ? U : never;
function parse(input: string): Result<number> {
const n = Number(input);
return Number.isNaN(n)
? { ok: false, error: new Error(`Not a number: ${input}`) }
: { ok: true, value: n };
}
type Names = ElementOf<string[]>; // string
const r = parse("12");
console.log(r.ok ? r.value * 2 : r.error.message);Result<T, E> is a generic union. Narrowing on ok works for any T. This pattern cannot be written as an interface, because an interface cannot be a union.
When a conditional type is given a union, it distributes over each member. ElementOf<string[] | number[]> is string | number. To prevent that, wrap both sides in a tuple: [T] extends [(infer U)[]].
Generic recursive shapes
Both constructs can refer to themselves, which is how you describe trees and linked structures.
interface TreeNode<T> {
value: T;
children: TreeNode<T>[];
}
type Json =
| string
| number
| boolean
| null
| Json[]
| { [key: string]: Json };
const tree: TreeNode<string> = {
value: "root",
children: [{ value: "leaf", children: [] }],
};
const doc: Json = { name: "x", tags: ["a", "b"], meta: { n: 1 } };
console.log(tree.children[0].value, doc);Recursion through object properties and arrays has been allowed for a long time. A direct alias that refers to itself with nothing in between, such as type Bad = Bad | string, is an error.
How the declaration forms compare
| Question | Generic interface | Generic type alias |
|---|---|---|
| Accepts type parameters and defaults | Yes | Yes |
| Accepts constraints with `extends` | Yes | Yes |
| Can name a union or tuple | No | Yes |
| Can use conditional types | No | Yes |
| Can be extended by another interface | Yes | Only if it resolves to an object type |
| Can be merged by redeclaring | Yes, with the same parameters | No |
Declaration merging has one generic-specific rule. When two interface declarations share a name, every declaration must list identical type parameters, including names, constraints, and defaults. A mismatch is an error.
Common errors
- Unused parameters. A parameter that never appears in the body is legal but meaningless, because structural typing ignores it.
interface Tag<T> {}accepts the same values for anyT. Remove it, or use it. - Using
anyas the default. It silently disables checking. Preferunknown. - Forgetting that arguments are not inferred in annotations. Write
Box<number>, or use a generic function to infer. - Over-constraining.
T extends objectrejectsstring. Constrain to the least you need. - Declaring the parameter at the wrong level. See the
MapperAandMapperBcomparison above.
Exercises
Exercise
Write a generic interface Cache<TKey extends string | number, TValue = unknown> with methods get(key: TKey): TValue | undefined and set(key: TKey, value: TValue): void. Then state the type of Cache<string> when used as a variable annotation, and say whether Cache<boolean> compiles.
Show answer
interface Cache<TKey extends string | number, TValue = unknown> { get(key: TKey): TValue | undefined; set(key: TKey, value: TValue): void; }. Cache<string> means TKey is string and TValue falls back to unknown, so get returns unknown and set accepts unknown. Cache<boolean> does not compile, because boolean does not satisfy the constraint string | number.
Exercise
Why can Result<T, E> be written as a type alias but not as an interface, and what technique lets you read value safely from it?
Show answer
Result is a union of two object types, and only a type alias can name a union. You read value safely by narrowing on the ok discriminant: inside a check of r.ok being true, TypeScript knows the member is { ok: true; value: T }.
Exercise
What is the difference between interface A<T> { (x: T): T } and interface B { <T>(x: T): T }?
Show answer
In A, T is fixed when the type is named, so A<string> only accepts and returns strings. In B, T belongs to the call signature, so each call chooses its own T and a single value can be used with strings, numbers, or anything else.