Sub topic 12
Generic interfaces and type aliases
Assume you know basic TypeScript annotations, JavaScript objects, functions, and classes. You should also be able to run the TypeScript compiler or read type errors in an editor.
A generic type is a type definition with a placeholder. The placeholder is a type parameter, usually written with a name such as T. When you use the generic, you provide a concrete type for that parameter.
Generics let one shape preserve useful type information for many different types.
The working model
An interface can be generic:
interface Box<T> {
value: T;
}
const numberBox: Box<number> = { value: 42 };
const messageBox: Box<string> = { value: "ready" };
console.log(numberBox.value.toFixed(1)); // 42.0
console.log(messageBox.value.toUpperCase()); // READYBox<T> describes an object with a value property. Box<number> replaces T with number, while Box<string> replaces it with string.
A type alias can also be generic:
type Pair<Left, Right> = [Left, Right];
const entry: Pair<string, number> = ["age", 30];Here, Pair<string, number> is a tuple whose first item is a string and whose second item is a number.
The type parameters belong to the declaration, not to a specific property name. Their purpose is to connect related types. In Box<T>, the type used for the property is the same type supplied by the caller.
Constraints and defaults
Use an extends constraint when the generic needs a known capability:
interface HasId {
id: number;
}
function getId<T extends HasId>(item: T): number {
return item.id;
}
const user = { id: 7, name: "Grace" };
console.log(getId(user)); // 7T extends HasId means that callers may provide HasId or any more specific type. Without the constraint, TypeScript would not allow item.id, because an unconstrained T might not have an id property.
A generic parameter can have a default:
interface ApiResponse<T = string> {
data: T;
status: number;
}
const textResponse: ApiResponse = { data: "ok", status: 200 };
const userResponse: ApiResponse<{ name: string }> = {
data: { name: "Ada" },
status: 200,
};The first declaration uses the default string. The second supplies an object type explicitly.
| Form | Use |
|---|---|
| `interface Box<T>` | A reusable object shape |
| `type Pair<A, B>` | A reusable alias, tuple, union, or combination |
| `T extends X` | Require a capability or structure |
| `T = X` | Provide a default type argument |
Common errors
Do not use any when the generic should preserve the caller's type. any removes checking, while T carries the type through the definition.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const firstName = first(["Ada", "Grace"]);
// firstName is string | undefinedA common mistake is assuming a constraint changes T into exactly that constraint. It does not. In T extends HasId, an object can still have additional properties, and those properties remain part of the inferred type.
Use a type argument when inference cannot determine the intended type, or when you want to make an important choice explicit.
Exercise
Define a generic type alias named Result that represents either a successful value of type T or an error message. Then create a Result<number> containing 42.
Show answer
type Result<T> = { ok: true; value: T } | { ok: false; error: string }; const result: Result<number> = { ok: true, value: 42 };