Generic functions
A function that only ever handles one type is easy to type: (x: number) => number. A function meant to work with any type, while still keeping track of exactly which one it was given, needs a type parameter — written <T> right after the function name. T is a placeholder the compiler fills in with a real type at each call site.
You should see
42
helloidentity2<T>(a: T, b: T): T, returning whichever one is truthy, and call it with two numbers.function identity<T>(x: T): T {return x}const a = identity(42)const b = identity("hello")console.log(a, b)
identity(42) is called. The compiler infers T = number just to type-check this one call — at runtime T does not exist at all; x is simply the value 42, an ordinary function argument.
x | 42 |
All 4 steps as a table
| Step | Line | What happened | Variables now |
|---|---|---|---|
| 1 | 4 | identity(42) is called. The compiler infers T = number just to type-check this one call — at runtime T does not exist at all; x is simply the value 42, an ordinary function argument. | x = 42 |
| 2 | 2 | Returns x unchanged. | a = 42 |
| 3 | 5 | identity("hello") is a separate call. T is inferred as string this time, purely for the compiler — the function body that actually runs is identical bytecode either way. | b = 'hello' |
| 4 | 6 | Prints both results. |
.toUpperCase() on the result. A generic preserves the type through the function; any discards it.- Type parameter
- A placeholder type, conventionally named T, U, K, V, declared in angle brackets and filled in by the compiler at each call.
- Generic function
- A function whose parameter or return types are expressed in terms of one or more type parameters instead of a fixed type.
JuniorWhy use a generic function instead of typing a parameter as any?
any turns type checking off entirely for that value — you lose autocomplete and every future safety check on it. A type parameter like T preserves the actual type through the function: pass in a number and you get a number back, with the compiler aware of that the whole way, instead of writing a separate overload for every type you might pass.
What they are really testing: Whether the candidate understands the safety a generic preserves, not just that both compile.
