Basic Generics

Passing types as variables.

TypeScript5 min readConcept 23 of 54

Variables for Types

Generics allow you to write reusable code that works with any data type, without losing strict type checking.

Just like a function takes a *value* variable as an argument, a generic function takes a *type* variable (usually called <T>) as an argument.

The 'any' trap

If you write a function getFirstItem(arr: any[]): any, it accepts anything, but when it returns the first item, you have no idea what type that item is. You lost the type safety.

If you use generics getFirstItem<T>(arr: T[]): T, TypeScript tracks exactly what type you passed in. If you pass an array of numbers, it guarantees the return type is a number.

Syntax

typescript // <T> declares the type variable. // We use T for the array argument, and T for the return type. function getFirstItem<T>(arr: T[]): T | undefined { return arr[0]; } // Explicitly passing the type (optional, but clear): const a = getFirstItem<number>([1, 2, 3]); // 'a' is number // Implicitly inferred by TypeScript: const b = getFirstItem(["apple", "banana"]); // 'b' is string

Try it

Select a type to pass into the generic function. Watch how the type variable <T> cascades through the signature, replacing the placeholders and locking the return type.

function getFirst<
T
>(arr: 
T
[]): 
T
 {
return arr[0];
}

// Caller determines the type of T
const res = getFirst
<T>
([]);
Type Resolution
TT

Select a type variable to pass to the function.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Why are Generics better than using the 'any' type for a reusable function?

Remember this

  • Generics <T> act as variables for types.
  • They allow a function to adapt to any type while maintaining strict checking.
  • The compiler can often infer <T> automatically from the arguments you pass.
  • Generics prevent the loss of type safety caused by any.

Done with this concept?

Mark it complete to track your progress. No login needed.