Default type parameters

The value a type parameter takes when it isn’t provided or inferred.

On this page

Example

#
TypeScript
type ApiResult<TData = unknown, TError = string> =
  | { ok: true; data: TData }
  | { ok: false; error: TError }

const plain: ApiResult = { ok: false, error: 'timeout' }
const typed: ApiResult<number[]> = { ok: true, data: [1, 2, 3] }

console.log(plain.ok ? 'data' : plain.error)
console.log(typed.ok ? typed.data.length : 0)
Result
timeout
3

Definition and usage

#

A type parameter can have a default value, written just like in functions: type Response<T = unknown>. If someone uses the type without providing the parameter, the default value is used.

This makes generic types easier to use in simple cases, without losing flexibility in complex ones. That’s how, for example, Promise works in many libraries, or React component types.

Parameters with default values must come after required parameters, and the default value must satisfy any extends constraint.

Syntax

#
Syntax
type Name<T = DefaultType> = …
function f<T = DefaultType>() { … }

Good practices

#
  • Default type parameters are a good place for unknown, which forces you to check the data, instead of any.
  • Put the parameters that change most often at the start of the list, and the ones with sensible default values at the end.

Related entries

#

Spotted a mistake or missing an example? Write to us.