unknown in Generic Constraints
You'll learn: How to use unknown as a constraint when you need a type parameter but don't want to implicitly accept any.
The Problem: When You Need a Type Parameter But No Specific Shape
Sometimes you write a generic function that genuinely works with any type, but you want to avoid the safety issues of any. You might be tempted to write:
function identity<T>(value: T): T {
return value;
}
This works fine. But what if you want to be explicit that you're accepting anything, while maintaining type safety? That's where unknown as a constraint comes in.
The Pattern: <T extends unknown>
When you write <T extends unknown>, you're saying: "This type parameter can be anything, but we're being explicit about it—and we won't treat it as any."
function safeIdentity<T extends unknown>(value: T): T {
return value;
}
This looks identical to the unconstrained version in practice, but it signals intent: you've consciously allowed all types, not just forgotten to add a constraint.
Why This Matters
The real power shows up when you want to prevent accidentally using any:
function process<T extends unknown>(input: T): void {
// T could be anything, but you can't do arbitrary operations
console.log(input); // OK
// input.someMethod(); // Error: we don't know if this exists
}
Unlike any, unknown forces you to narrow or assert before using the value in unsafe ways—even in generic contexts.
When to Use This
Use <T extends unknown> when you're being deliberately generic and want to document that you've thought about the type safety implications. It's more about communication than functionality—the constraint doesn't restrict anything, but it makes your intentions clear.
Key Takeaway: <T extends unknown> lets you accept any type in a generic while maintaining type safety and signaling that the broad acceptance is intentional, not accidental.