Sub topic 1
Why Unconstrained Type Parameters Are Limiting
Prerequisites
This chapter assumes you know the following:
- Basic TypeScript types, interfaces, and type aliases.
- How to write and call a simple generic function such as
identity<T>(x: T): T. - Union types and object types.
- The
keyofoperator and indexed access types (T[K]) help, but you do not need them yet.
The chapter covers why a bare type parameter limits what a function body can do. It also shows the errors you will see and the workarounds that look tempting but fail. The next chapter introduces the fix, extends constraints.
What a type parameter means inside the function body
A generic function is written once and checked once. TypeScript does not re-check the body for every call. It checks the body against the type parameter T as an unknown placeholder, and it must accept every type a caller could ever supply.
That has a consequence. Inside the body, TypeScript may only use operations that are valid for all possible types. For a bare T with no constraint, the set of such operations is very small.
function identity<T>(value: T): T {
return value;
}This works because the body does nothing with value except pass it along. Passing a value around is valid for every type.
The first error: reading a property
Suppose you want a function that returns the longer of two values. The natural first attempt reads .length.
function longest<T>(a: T, b: T): T {
return a.length >= b.length ? a : b;
// Error: Property 'length' does not exist on type 'T'.
}The error is correct. T could be number, boolean, null, or an object with no length. TypeScript cannot know that the caller will pass something with a length, so it refuses to compile the body. The error is reported at the definition, not at the call site, which is the main difference from how templates work in some other languages.
Why the check happens at the definition
Think of the signature as a contract with two sides.
- The caller promises to supply some type for
T. The caller can pick anything. - The body promises to work for whatever the caller picked.
An unconstrained T gives the body no information about what the caller picked. If the body could read .length, then longest(10, 20) would compile and fail at runtime, because (10).length is undefined and the comparison undefined >= undefined is false. The error prevents that.
The block above is intentionally left out. Use the diagram below instead.
What you can do with an unconstrained T
It helps to list the operations that do compile, so you know where the boundary is.
| Operation on a value of type `T` | Compiles? | Reason |
|---|---|---|
| Return it | Yes | Same type in, same type out |
| Assign it to another `T` variable | Yes | Types match |
| Store it in `T[]` or `{ value: T }` | Yes | The container holds any `T` |
| Pass it to a parameter typed `unknown` | Yes | Every type is assignable to `unknown` |
| Compare with `===` against another `T` | Yes | Equality is defined for all values |
| Read a property such as `.length` | No | Not every type has it |
| Call it as a function | No | Not every type is callable |
| Use `+`, `<`, or `>` | No | Not every type supports the operator |
| Use `new` on it | No | Not every type is a constructor |
The pattern is clear. A bare T behaves like unknown that remembers which type it was. You can move it, store it, and compare it. You cannot look inside it.
The same limit applies to the whole family of operations
The .length error is the most common one, but the same reasoning produces several related errors.
function double<T>(x: T): T {
return x * 2;
// Error: The left-hand side of an arithmetic operation must be of type
// 'any', 'number', 'bigint' or an enum type.
}
function callIt<T>(fn: T): void {
fn();
// Error: This expression is not callable.
// Type 'unknown' has no call signatures.
}
function makeOne<T>(ctor: T): void {
new ctor();
// Error: This expression is not constructable.
}In each case the reason is the same. The body needs a capability, and nothing in the signature guarantees it.
Tempting workarounds that do not solve the problem
Faced with the .length error, developers often reach for one of three escape hatches. Each one removes the error, and each one gives up something you wanted from generics.
Workaround 1: use `any`
function longestAny(a: any, b: any): any {
return a.length >= b.length ? a : b;
}
const r = longestAny(10, 20); // compiles, r is any, runtime result is wrongThis compiles, but you have lost two things. The call longestAny(10, 20) is no longer rejected. The return type is any, so every later use of r is unchecked, and the lack of checking spreads to the code that uses it.
Workaround 2: use a type assertion
function longestCast<T>(a: T, b: T): T {
const x = a as unknown as { length: number };
const y = b as unknown as { length: number };
return x.length >= y.length ? a : b;
}
longestCast(10, 20); // compiles, but no error is reported for numbersThe assertion tells the compiler to stop checking. The signature still says "any T", so callers can pass numbers, and the bug moves to runtime. An assertion is a promise from you to the compiler. Here nothing enforces the promise.
Workaround 3: widen the parameter to a concrete type
function longestFixed(a: { length: number }, b: { length: number }) {
return a.length >= b.length ? a : b;
}
const s = longestFixed("ab", "abc"); // return type: { length: number }
s.toUpperCase(); // Error: the string type was lostThis is safe, and it rejects numbers. However, the return type is the narrow shape { length: number }, not the type that was passed in. The caller passed strings and got back something that no longer knows it is a string. The generic's main benefit, linking the output type to the input type, is gone.
The following table compares the options.
| Approach | Rejects bad arguments | Keeps the caller's type in the result | Body is type-checked |
|---|---|---|---|
| Unconstrained `T` | Not applicable, the body fails to compile | Yes | Yes |
| `any` | No | No | No |
| Assertion on `T` | No | Yes | No |
| Concrete parameter type | Yes | No | Yes |
| Constrained `T` (next chapter) | Yes | Yes | Yes |
Only the last row has all three properties. That is the reason constraints exist.
Seeing the gap at the call site
The limitation also shows up from the caller's side, not only inside the body. An unconstrained signature tells callers nothing about what is acceptable.
function pluck<T>(items: T[], key: string): unknown[] {
return items.map(item => item[key]);
// Error: Element implicitly has an 'any' type because expression of
// type 'string' can't be used to index type 'unknown'.
}Two problems appear here. The body cannot index item because T is opaque. Even if it could, key: string would accept "nonsense", and the return type unknown[] throws away the type of the property. A well-typed version needs to say "T has a property named key, and the result has that property's type". That is exactly what a constraint combined with keyof expresses. You will build it in a later chapter.
A mental model: the constraint is a lower bound on what you know
An unconstrained type parameter has an implicit constraint. TypeScript treats <T> as if it were <T extends unknown>. You can write it out and confirm the behavior is identical.
function same<T extends unknown>(x: T): T {
return x;
}Seen this way, the question is not "constraint or no constraint". Every type parameter has a constraint, and the default is the weakest one, unknown. The body can use only what the constraint guarantees. Choosing a stronger constraint gives the body more to work with and gives callers fewer valid arguments.
The trade-off runs in both directions.
- A weak constraint accepts many arguments and lets the body do little.
- A strong constraint accepts fewer arguments and lets the body do more.
Good API design picks the weakest constraint that still lets the body do its job. A function that only reads .length should require { length: number }, not string | unknown[], so that other length-bearing types still work.
Common mistakes at this stage
- Expecting the error at the call site. The error for
a.lengthappears in the function body, even if every real caller passes strings. TypeScript does not look at callers when checking the body. - Fixing the error with
any. This silences the compiler and removes the safety of the call as well. - Narrowing with
typeofand thinking it constrainsT. A check such astypeof a === "string"narrows the value inside one branch. It does not change which arguments callers may pass. This is covered with the pitfalls chapter. - Believing generics are checked per instantiation. TypeScript checks the declaration once. This is why a body that would work for every call you have written can still be rejected.
Checking your understanding
Exercise
A colleague writes function firstChar<T>(s: T): string { return s[0]; } and gets an error. In one or two sentences, explain why TypeScript rejects it even though every current caller passes a string.
Show answer
The body is checked once against the placeholder T, which has the implicit constraint unknown. Not every type can be indexed with [0], so the compiler rejects the body at the definition regardless of what the current callers pass.
Exercise
Which of these statements compile when x has the unconstrained type T? (a) const y: T = x; (b) const n: number = x.length; (c) const arr: T[] = [x, x]; (d) const u: unknown = x;
Show answer
(a), (c), and (d) compile. (b) fails because T has no known length property.
Exercise
Why does function longestFixed(a: { length: number }, b: { length: number }) fix the error but still fall short of what a constrained generic provides?
Show answer
It rejects arguments without a length, but its return type is { length: number }. The caller's specific type, such as string, is lost in the result, so the output is no longer linked to the input type.