Course contentsShow
← TypeScript
Lesson 538 of 1,79613. GenericsFree lesson

Your First Generic Function

Writing a simple identity function with a type parameter to preserve input and output types.

Your First Generic Function

You'll learn how to write a simple generic function that preserves the type relationship between its input and output.

The Problem Without Generics

Imagine you want to write a function that takes a value and returns it unchanged — an "identity" function. Without generics, you'd lose type information:

function identity(value: any): any {
  return value;
}

const result = identity(42); // result is type `any` — we lost the fact it's a number!

Using any defeats the purpose of TypeScript. You pass in a number, but TypeScript forgets that detail.

Introducing Type Parameters

A generic function uses a type parameter (written in angle brackets) to capture the type you pass in:

function identity<T>(value: T): T {
  return value;
}

const num = identity(42);        // num is type `number`
const text = identity("hello");  // text is type `string`

Here, T is a type variable — a placeholder that TypeScript fills in based on what you pass. When you call identity(42), TypeScript infers T = number, so the return type becomes number.

How It Works

Think of <T> as declaring a type variable, just like (value) declares a value variable. TypeScript connects the input type to the output type through T, preserving exact type information.

You can also specify the type explicitly:

const result = identity<boolean>(true); // T is explicitly set to boolean

Key Takeaway: A generic function uses type parameters (like <T>) to create a type relationship between inputs and outputs, preserving type safety without losing specificity.