BeginnerCoder

Lesson 14 — Generics

Types as parameters

A generic function has a type parameter in angle brackets, usually called T. T is a placeholder that gets filled in at each call: call it with a number and T is number, with a string and T is string. You get one function that works for any type and still keeps exact types.

function echo<T>(value: T): T { return value; }
const n = echo(5);      // n: number
const s = echo("hey");  // s: string

Why it matters: arrays, Promises and React's useState are all generic — this is how libraries stay type-safe.

Want it another way?
Task

Make wrap generic so it accepts any type, and return the value inside an array. Expect [ 5 ], then [ 'hi' ].

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.