Generic Declarations
What you'll learn: How to add type parameters to functions, classes, and interfaces in .d.ts files to describe APIs that work with multiple types.
The Problem with Concrete Types in Declarations
When writing declaration files for libraries, you often encounter functions, classes, or interfaces that work with many different types. If you only use concrete types like string or number, you lose the generic nature of the API.
Adding Type Parameters to Declarations
Just like you write generics in regular TypeScript code, you can declare them in .d.ts files. The syntax is identical—you add angle brackets with type parameter names to your function, class, or interface declarations.
Generic Function Declaration
// mylibrary.d.ts
declare function identity<T>(arg: T): T;
declare function map<T, U>(
array: T[],
callback: (item: T) => U
): U[];
Generic Interface Declaration
// mylibrary.d.ts
interface Container<T> {
value: T;
getValue(): T;
setValue(value: T): void;
}
declare const stringContainer: Container<string>;
Generic Class Declaration
// mylibrary.d.ts
declare class Box<T> {
constructor(value: T);
value: T;
map<U>(fn: (value: T) => U): Box<U>;
}
Multiple Type Parameters
You can declare multiple type parameters just as you would in implementation code:
declare function merge<T, U>(first: T, second: U): T & U;
declare class Pair<K, V> {
constructor(key: K, value: V);
key: K;
value: V;
}
When to Use Generic Declarations
Use generic declarations when the library's JavaScript implementation is generic in nature—when functions or classes preserve type relationships between inputs and outputs. This gives users of your declaration file the same type safety they'd get from a fully-typed codebase.
Key Takeaway: Generic declarations in .d.ts files use the same syntax as regular TypeScript generics—add type parameters to functions, classes, and interfaces to accurately describe APIs that work across multiple types while preserving type relationships.