How do you declare a generic type via type?
In TypeScript you can declare generic types not only in functions and classes, but also with the type keyword.
This is especially useful for universal structures, utility types, and wrappers around other types.
The basic syntax
javascript
type TypeName<T> = ...;Tis the type parameter (generic).- Inside the definition you can use
Tlike a regular type.
Example 1: a wrapper around a type
javascript
type Box<T> = {
value: T;
};
const stringBox: Box<string> = { value: "Hello" };
const numberBox: Box<number> = { value: 42 };
Box<T>is a generic type that can be used with any data type.
Example 2: an array of a specific type
javascript
type ArrayOf<T> = T[];
const strings: ArrayOf<string> = ["a", "b"];
const numbers: ArrayOf<number> = [1, 2, 3];Here
ArrayOf<T>is equivalent toT[], but it can be extended if needed (for example, to add metadata).
Example 3: a conditional type inside a generic
javascript
type Nullable<T> = T | null | undefined;
const name: Nullable<string> = null;
const age: Nullable<number> = 30;Often used to describe optional or nullable fields.
Example 4: a type with a constraint (extends)
javascript
type HasId<T extends { id: string }> = T & { createdAt: Date };
const user: HasId<{ id: string; name: string }> = {
id: "u1",
name: "Tim",
createdAt: new Date(),
};
T extends { id: string }is a constraint: only types that have anid.
Example 5: several generic parameters
javascript
type Pair<T, U> = [T, U];
const p1: Pair<string, number> = ["age", 25];
const p2: Pair<boolean, string> = [true, "done"];Example 6: a dependency between parameters
javascript
type PropertyType<T, K extends keyof T> = T[K];
interface User {
id: number;
name: string;
}
type UserId = PropertyType<User, "id">; // number
type UserName = PropertyType<User, "name">; // stringExample 7: a generic utility type
javascript
type WithOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
interface User {
id: number;
name: string;
age: number;
}
type OptionalName = WithOptional<User, "name">;
// { id: number; age: number; name?: string }Example 8: a default value for a generic
javascript
type Response<T = string> = {
data: T;
success: boolean;
};
const r1: Response = { data: "ok", success: true }; // T = string
const r2: Response<number> = { data: 200, success: true }; // T = numberSummary
| Capability | Example |
|---|---|
| A single parameter | type Box<T> = { value: T } |
| Several parameters | type Pair<T, U> = [T, U] |
| A type constraint | type HasId<T extends { id: string }> |
| Dependent parameters | type Prop<T, K extends keyof T> = T[K] |
| A default value | type Response<T = string> |
| A conditional generic | `type Nullable |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.