Skip to main content

Default type in a generic

In TypeScript you can specify a default type for a generic parameter, just like for function arguments. This is called a default generic type parameter.


Syntax

javascript
type MyType<T = DefaultType> = ...

or for a function:

javascript
function myFunc<T = DefaultType>(arg: T) { ... }

If the type is not explicitly specified when using the generic type or function, TypeScript uses the default value.


Example 1: a default type in a function

javascript
function wrap<T = string>(value: T): { data: T } { return { data: value }; } wrap("hi"); // T = string (from the argument) wrap(42); // T = number (inference) wrap(); // T = string (default type)

Here, if TypeScript cannot infer the type T, it takes string.


Example 2: a default type in a type definition

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 = number

Often used to simplify using a type without having to explicitly specify the generic.


Example 3: several parameters with different default values

javascript
type Pair<T = string, U = number> = [T, U]; const a: Pair = ["age", 25]; // [string, number] const b: Pair<boolean, string> = [true, "ok"]; // [boolean, string]

Example 4: usage in interfaces

javascript
interface ApiResponse<T = any> { data: T; error?: string; } const res1: ApiResponse = { data: "ok" }; // T = any const res2: ApiResponse<number> = { data: 42 }; // T = number

Example 5: in functions with a constraint (extends)

javascript
function getValue<T extends object = { id: number }>(obj: T): T { return obj; } getValue(); // T = { id: number }

Important

  1. The default type is used only when TypeScript could not infer the type.
  2. If the type can be inferred from the argument, the default value is ignored.
  3. In the list of generic parameters, a parameter with a default must come after parameters without one:
javascript
// ok type Example<T, U = string> = ... // Error type Bad<U = string, T> = ...

Summary

CapabilityExampleDescription
Default type<T = string>Used when TS could not infer the type
In a type definitiontype Box<T = number>A universal structure
In a functionfunction fn<T = any>()Often for a fallback type
With a constraint<T extends object = {}>Can be combined with extends
Parameter order<T, U = string>Required first, then ones with defaults

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.