0
0
Typescriptprogramming~5 mins

Default generic types in Typescript

Choose your learning style9 modes available
Introduction

Default generic types let you set a fallback type for a generic. This means if no type is given, the default is used automatically.

When creating reusable functions or classes that usually work with one type but can accept others.
When you want to make your code easier to use by not forcing users to always specify a type.
When you want to provide a common type but still allow flexibility for special cases.
Syntax
Typescript
function example<T = string>(value: T): T {
  return value;
}

The = string after T sets the default type.

If you call example() without specifying T, it uses string.

Examples
This function returns the argument. If no type is given, it assumes number.
Typescript
function identity<T = number>(arg: T): T {
  return arg;
}
Shows calling the function with and without specifying the type.
Typescript
const result = identity(42); // T is number by default
const text = identity<string>("hello"); // T is string explicitly
A class with a generic type defaulting to boolean.
Typescript
class Box<T = boolean> {
  value: T;
  constructor(value: T) {
    this.value = value;
  }
}
Sample Program

This function wraps a value in an array. If no type is given, it assumes string. We show both default and explicit usage.

Typescript
function wrapInArray<T = string>(item: T): T[] {
  return [item];
}

const defaultArray = wrapInArray('hello');
const numberArray = wrapInArray<number>(123);

console.log(defaultArray);
console.log(numberArray);
OutputSuccess
Important Notes

Default generic types make your code friendlier and reduce the need to always specify types.

You can override the default by providing a type when calling the function or creating an instance.

Summary

Default generic types provide a fallback type for generics.

They make code easier to use without losing flexibility.

You can still specify a different type when needed.