Generics
Prerequisites: Functions with types
A generic lets a function or class work with any type, while still
keeping full type safety — instead of writing the same logic once per
type, or giving up and using any.
Syntax
function firstItem<T>(items: T[]): T {
return items[0];
}
Example
const firstNumber = firstItem([1, 2, 3]); // inferred as number
const firstName = firstItem(["Ada", "Grace"]); // inferred as string
T is a placeholder for "whatever type is actually passed in" —
TypeScript infers it from the argument, and the return type
automatically matches, giving you both flexibility and safety at
once.
Practice
Write a generic function wrapInArray<T>(value: T): T[] that
returns a one-element array containing the value.
Show solution
function wrapInArray<T>(value: T): T[] {
return [value];
}