← Back to TypeScript Course | Chapter 7: Generics | Lesson 2 of 8

Generic Functions

Generic functions use type parameters to work safely with different types. They are especially useful when the relationship between input and output types should remain the same.

Creating a Generic Function

Put a type parameter after the function name and use it in the parameter and return types; this is what actually connects the input type to the output type instead of writing the function once per concrete type.

Example: Creating a Generic Function

typescript
function identity<T>(value: T): T {
  return value;
}
console.log(identity<number>(10));

Generic Functions with Arrays

Generic functions can accept arrays and return elements while preserving their element type, so calling the function on a string[] still gives back a string, not a value TypeScript has to widen to any.

Example: Generic Functions with Arrays

typescript
function firstElement<T>(arr: T[]): T {
  return arr[0];
}
console.log(firstElement(["a", "b", "c"]));

Generic Arrow Functions

Arrow functions can also declare generic type parameters, and are useful for compact utility functions like a generic identity or comparator that need to stay short but still fully type-safe.

Example: Generic Arrow Functions

typescript
const identity = <T,>(value: T): T => value;
console.log(identity(99));

Generic Functions with Objects

Generic functions can preserve the exact type of objects passed to them, so a function that just forwards or wraps a value doesn't accidentally erase useful information about that value's shape.

Example: Generic Functions with Objects

typescript
function wrap<T>(value: T): { data: T } {
  return { data: value };
}
console.log(wrap({ name: "Nia" }));

Explicit Type Arguments

You can explicitly provide a type argument (like identity<string>(x)) when you want to make the intended type clear, or when TypeScript's inference genuinely can't determine it from the arguments alone.

Example: Explicit Type Arguments

typescript
function identity<T>(value: T): T {
  return value;
}
console.log(identity<string>("explicit"));
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.