Ad space (banner)
Lesson 15 / 20

Generics (<T>)

This lesson covers generics (<T>), which let you build functions and types that work with a variety of different types. It's for anyone searching "TypeScript generics usage."

Generics are like a "type variable" whose actual type gets decided later. You declare a placeholder type with the symbol <T>, and fill in the concrete type (number, string, and so on) when it's actually used.

The example defines function firstItem<T>(arr: T[]): T. This function works with both a number array and a string array, and returns a correctly-typed value each time.

A common early mistake is asking "why not just use any?" Using any disables type checking entirely, whereas generics preserve type safety while keeping the relationship "the type returned matches the type of the array you passed in."

In real projects, generics are used heavily wherever "the types differ, but the flow of logic is the same" โ€” array-processing utility functions, or common API-communication logic.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run TypeScript directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)