Sub topic 1
Why Unconstrained Type Parameters Are Limiting
Prerequisites
You should know basic TypeScript types, interfaces, object types, union types, and simple generic functions such as identity<T>(value: T): T. Familiarity with keyof and indexed access types is helpful but not required.
A generic type parameter lets a function work with many types while preserving information about the specific type supplied by the caller. For example:
function identity<T>(value: T): T {
return value;
}
const count = identity(42); // type: number
const message = identity("hello"); // type: stringHere, T represents the type of value. TypeScript infers T from the argument and uses the same type for the return value.
An unconstrained type parameter is a type parameter with no requirements. In identity<T>, T could be a number, string, object, array, function, or any other type. This flexibility is useful, but it also means the function body cannot assume that T has any particular properties or operations.
What an Unconstrained Type Can Do
The function can safely return the value, store it, or pass it to another place that accepts the same type. It cannot safely access a property that might not exist.
function keep<T>(value: T): T {
return value;
}
function describe<T>(value: T): string {
return String(value);
}String(value) works because JavaScript can convert any value to text. However, this function does not:
function getLength<T>(value: T): number {
// return value.length;
return 0;
}The commented line causes an error similar to:
Property 'length' does not exist on type 'T'.The problem is not that strings and arrays lack a length property. They have one. The problem is that T might be a type that does not have one:
getLength("TypeScript"); // string has length
getLength([10, 20, 30]); // array has length
getLength(123); // number does not have lengthWhen TypeScript checks the function declaration, it must make the body safe for every type that could replace T, including number.
Why the Caller Does Not Fix the Body
It can seem as if the caller should determine what operations are valid. For example, if a caller passes a string, then reading .length would be safe. But a generic function is checked once, before any particular call is selected.
function getLength<T>(value: T): number {
// This must be valid for every possible T.
// return value.length;
return 0;
}
const textLength = getLength("hello");The call gives T the type string for that invocation, but it does not rewrite or recheck the function body as a string-specific function. The declaration must already be valid for all allowed instantiations of T.
This rule protects callers from unsafe assumptions. If TypeScript allowed the property access, the same function could later be called with a number and fail at runtime.
The Difference Between Knowing a Type and Preserving a Type
An unconstrained generic still preserves type identity. This function returns exactly the type it receives:
function firstValue<T>(items: T[]): T {
return items[0];
}
const firstNumber = firstValue([1, 2, 3]); // number
const firstName = firstValue(["Ada", "Lin"]); // stringThe function knows that the result is a T, but it does not know what members T has. These are separate abilities:
- Type preservation lets the function relate inputs and outputs.
- A constraint lets the function use guaranteed members of a type.
A generic function can preserve a type without being able to inspect it.
A Constraint Changes the Working Model
When a function needs a particular member, state that requirement in the type parameter:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
const longerText = longest("cat", "tiger"); // type: string
const longerList = longest([1, 2], [3, 4, 5]); // type: number[]T extends { length: number } does not mean that T must be exactly that object type. It means that every possible T must at least have a numeric length property. A string and an array satisfy the requirement, so the function can read .length safely while still returning the specific original type.
Choosing Whether to Constrain
Add a constraint when the implementation depends on a property or capability. Do not add one merely to make the type parameter look precise. A constraint narrows which arguments callers may provide, so it should describe a real requirement of the function.
If the function only stores, returns, or compares values without using a specific member, an unconstrained parameter may be the correct design. If the function needs a property, the next step is to express that property with extends.
Exercise
Why does function size<T>(value: T): number { return value.length; } fail to compile, even when every current call passes a string?
Show answer
Because an unconstrained T could be instantiated with a type such as number. The function body must be safe for every possible T, so length is unavailable until the parameter has a constraint.