Sub topic 8
Giving Type Parameters a Default
This chapter assumes that you know basic TypeScript types, interfaces, type aliases, and generic functions such as identity<T>(value: T): T. You should also understand union types and the keyof operator.
A generic type parameter normally requires a type argument or an inferred type. A default type parameter supplies a type when the caller does not provide one.
interface ApiResponse<TData = unknown> {
data?: TData;
error?: string;
}
const empty: ApiResponse = {};
const message: ApiResponse<string> = {
data: "Ready"
};In ApiResponse, TData defaults to unknown. Therefore, ApiResponse means ApiResponse<unknown> when no type argument is supplied. The caller can still choose another type by writing ApiResponse<string>.
A default type parameter makes an API easier to call without removing its flexibility.
Defaults on common generic declarations
You can use defaults on interfaces, type aliases, classes, and functions.
type Box<T = string> = {
value: T;
};
class Storage<T = string> {
private value: T;
constructor(value: T) {
this.value = value;
}
get(): T {
return this.value;
}
}
function parse<T = unknown>(json: string): T {
return JSON.parse(json) as T;
}
const textBox: Box = { value: "hello" };
const numberBox: Box<number> = { value: 42 };
const storage = new Storage("draft"); // T is inferred as string
const value = parse<number>("42"); // T is explicitly numberThe default on Box applies when the type argument is omitted. The Storage example gets its type from constructor inference, so its default is not needed for that call. The parse function has no argument whose type contains T, so TypeScript cannot infer T from the call. It uses the default unknown.
unknown is often safer than any for an uncertain result. You must check or narrow an unknown value before using it as a specific type.
Multiple defaults and ordering
A generic declaration can have several type parameters with defaults.
interface ApiResponse<TData = unknown, TError = Error> {
data?: TData;
error?: TError;
}
const a: ApiResponse = {};
const b: ApiResponse<string> = {
data: "ok"
};
const c: ApiResponse<string, { code: number }> = {
error: { code: 404 }
};In b, TData is string, while TError keeps its default of Error. Type arguments are supplied from left to right. You cannot skip the first parameter and provide only the second one.
A required type parameter must come before any parameter with a default.
interface Result<TValue, TError = Error> {
value?: TValue;
error?: TError;
}
// Invalid:
// interface Invalid<T = string, U> {}This ordering lets TypeScript understand which omitted arguments should receive defaults.
| Declaration | Valid? | Reason |
|---|---|---|
| `Box<T = string>` | Yes | The parameter has a default |
| `Result<T, E = Error>` | Yes | Required parameter comes first |
| `Invalid<T = string, U>` | No | A required parameter follows a default |
Defaults must satisfy constraints
A default is still checked against the parameter's constraint. If a type parameter extends string | number, its default must be a string or number.
type ValueBox<T extends string | number = string> = {
value: T;
};
const words: ValueBox = { value: "hello" };
const count: ValueBox<number> = { value: 3 };
// Invalid:
// type BadBox<T extends string | number = boolean> = {
// value: T;
// };The default string satisfies the constraint. boolean does not, so BadBox is rejected when it is declared.
Constraints and defaults answer different questions:
- A constraint says which types are allowed.
- A default says which allowed type to use when none is supplied.
Choosing useful defaults
Choose a default that is safe and useful for the common case. For a response wrapper, unknown communicates that the data has not been checked. For a collection, an empty object type may be appropriate when callers usually provide no extra configuration.
Avoid defaults that hide mistakes. A default of any permits nearly every operation and can remove valuable type checking. Use it only when the API deliberately supports unchecked values.
The later topic on inference examines these choices in more detail. For now, remember that a default is a fallback. It is not a replacement for inference, and it does not override an explicit type argument.
Exercise
What type does ApiResponse<string> use for TError when TError has the default Error?
Show answer
It uses Error, because the first type argument sets TData and the omitted trailing parameter keeps its default.