unknown in Generic Constraints
You'll learn: Why unknown is the safest choice for generic constraints when a type parameter can be anything but must be narrowed before use.
The Principle
When writing generic functions or types, you sometimes need to constrain a type parameter without being too specific. The temptation is to use any:
function process<T extends any>(value: T) {
// ...
}
But any disables type checking entirely. A better approach is unknown — it accepts anything while forcing you to validate before using the value.
Why unknown Works Better
Think of generic constraints like security checkpoints. Using any is like removing the checkpoint entirely — anything passes through unchecked. Using unknown means "we'll accept any package, but you must inspect it before opening."
// ❌ Less safe: any allows unsafe operations
function dangerousProcess<T extends any>(value: T) {
return value.toString(); // might fail at runtime
}
// ✅ Safer: unknown forces narrowing
function safeProcess<T extends unknown>(value: T) {
// Must narrow first
if (typeof value === 'string') {
return value.toUpperCase();
}
if (typeof value === 'number') {
return value.toFixed(2);
}
return String(value);
}
Real-World Application
This pattern shines in generic utilities that accept any input but must validate it:
function createValidator<T extends unknown>(validate: (value: T) => boolean) {
return (input: T): T => {
if (!validate(input)) {
throw new Error('Validation failed');
}
return input;
};
}
// Usage with narrowing inside validator
const validatePositive = createValidator<unknown>((value) => {
return typeof value === 'number' && value > 0;
});
The constraint <T extends unknown> signals: "This can be anything, but we'll handle it safely."
Key Takeaway: Prefer unknown over any as a generic constraint when you want maximum flexibility without sacrificing type safety — it forces deliberate narrowing instead of disabling checks.