Introducing Type Parameters
You'll learn: How to use the <T> syntax to create flexible, reusable functions that preserve type information.
What Are Type Parameters?
Type parameters are placeholders for types that get filled in when you call a function. They're written using angle brackets like <T>, where T is just a conventional name (you could use any identifier).
Think of type parameters like variables, but for types instead of values. Just as a function parameter name holds a value you pass in, a type parameter T holds a type that TypeScript infers or that you specify.
The Basic Syntax
Here's the identity function rewritten with a type parameter:
function identity<T>(value: T): T {
return value;
}
const num = identity(42); // T becomes number
const str = identity("hello"); // T becomes string
const bool = identity(true); // T becomes boolean
The <T> declares a type parameter. The (value: T) says the parameter uses that type. The : T says the return type matches it too.
Why This Matters
Without type parameters, you'd lose the specific type:
function identityLoose(value: unknown): unknown {
return value;
}
const result = identityLoose(42); // result: unknown (type lost!)
With <T>, TypeScript remembers what type you passed in and carries it through to the return type. It's determined fresh at call time for each invocation.
Key Takeaway: Type parameters use <T> syntax to create placeholders for types that TypeScript fills in when you call the function, preserving type safety while keeping code reusable.