Sub topic 14
Common Pitfalls and Good Practice
This chapter collects the mistakes that show up most often in generic TypeScript code and the habits that avoid them. It assumes you have read the earlier chapters on type parameters, inference, constraints with extends, and conditional types. Each section names one problem, shows it, and gives a fix.
A type parameter that appears only once
A type parameter earns its place by relating two or more positions in a signature: an argument to the return type, or one argument to another. If T appears once, it relates nothing.
// Unnecessary type parameter: T appears only once
function logValue<T>(value: T): void {
console.log(value);
}
// Simpler and equivalent
function logValueSimple(value: unknown): void {
console.log(value);
}Both functions accept any argument and return nothing. The generic version adds noise and suggests a relationship that does not exist. Before writing <T>, ask where else T is used. If the answer is nowhere, use a plain type.
Generics that only appear in the return type
A special case of the same problem is a type parameter that appears only in the return type. The caller picks T, and nothing checks that choice.
function parseJson<T>(text: string): T {
return JSON.parse(text); // JSON.parse returns any, so this compiles
}
const user = parseJson<{ id: number }>("{}");
console.log(user.id); // typed as number, but the value is undefinedThis is a type assertion in disguise. The compiler trusts the type argument, and the runtime value can be anything. A more honest signature returns unknown and makes the caller narrow the result, or validates the data with a schema library.
function parseJsonSafe(text: string): unknown {
return JSON.parse(text);
}
const value = parseJsonSafe('{"id": 1}');
if (typeof value === "object" && value !== null && "id" in value) {
console.log(value.id);
}Inference widens literals
When TypeScript infers T from a value, it usually widens a literal such as "a" to its base type string. A constraint changes that: if T is constrained to a primitive type, the literal type is kept.
function box<T>(v: T) {
return { v };
}
function boxLiteral<T extends string>(v: T) {
return { v };
}
const a = box("a"); // { v: string }
const b = boxLiteral("a"); // { v: "a" }Use this when the exact literal matters, for example when a string selects a property or a branch. Do not add extends string only to keep literals if you do not need them, because the constraint also rejects non-string arguments.
Conflicting inference candidates
When one type parameter is used for several arguments, TypeScript collects a candidate from each and has to pick one. If the candidates are unrelated, you get an error on one of the arguments.
function merge<T>(a: T, b: T): T[] {
return [a, b];
}
// merge(1, "a"); // Error: Argument of type 'string' is not assignable to parameter of type 'number'
const ok = merge<string | number>(1, "a"); // (string | number)[]You have two fixes. Supply the union explicitly, as above, or give each argument its own type parameter (<A, B>(a: A, b: B): (A | B)[]). Choose by intent. If the arguments must have the same type, one parameter is right and the error is useful. If they may differ, use two.
No partial type argument lists
You cannot supply some type arguments and let TypeScript infer the rest. It is all or nothing.
function convert<TInput, TOutput>(
input: TInput,
fn: (value: TInput) => TOutput
): TOutput {
return fn(input);
}
// convert<number>(5, String); // Error: Expected 2 type arguments, but got 1.
const text = convert(5, String); // inferred: string
const text2 = convert<number, string>(5, String); // fully explicitDefault type parameters do not change this. A default is used when the argument is omitted and cannot be inferred, but once you write any angle brackets, inference for that call is switched off and defaults fill the gaps. If you often need to set only the first parameter, split the API into two steps, such as a function that takes the first type and returns another function that infers the second.
In most call sites, leaving out type arguments entirely is best. Explicit arguments are for the cases where inference picks something wrong or where there is nothing to infer from.
Returning the constraint instead of `T`
A constraint tells you what the body may assume about T. It does not tell you what T is. A value that satisfies the constraint is not necessarily a T.
interface HasId {
id: number;
}
// function reset<T extends HasId>(item: T): T {
// return { id: 0 };
// // Error: '{ id: number; }' is assignable to the constraint of type 'T',
// // but 'T' could be instantiated with a different subtype of constraint 'HasId'.
// }
function reset<T extends HasId>(item: T): T {
return { ...item, id: 0 };
}If T is { id: number; name: string }, the literal { id: 0 } is missing name, so it is not a valid T. Spreading the original value keeps every property of T and overrides only id. If the function really does produce a plain HasId, change the return type to HasId and drop the claim about T.
Casting your way out
When a generic body fails to compile, as T often silences the error. It also removes the check that was protecting you.
function makeEmpty<T extends HasId>(): T {
return {} as T; // compiles, but the result has no id at runtime
}Treat an as T in a generic function as a signal to reconsider the design. Typical better options are to take a factory function as an argument (create: () => T), to take an existing value and copy it, or to return a less specific type. If the assertion is genuinely safe, keep it small and comment on why.
Conditional types over `never` and unions
Conditional types written over a bare type parameter distribute across unions. That is often what you want, but it has two side effects.
type ToArray<T> = T extends unknown ? T[] : never;
type Distributed = ToArray<string | number>; // string[] | number[]
type ToArrayWhole<T> = [T] extends [unknown] ? T[] : never;
type NotDistributed = ToArrayWhole<string | number>; // (string | number)[]First, the result for a union is a union of per-member results, which may not match what you meant. Second, never is an empty union, so a distributive conditional applied to never produces never and ignores both branches. To test for never itself, wrap both sides in tuples.
type IsNever<T> = [T] extends [never] ? true : false;
type A = IsNever<never>; // true
type B = IsNever<string>; // falseWrapping in a tuple is the standard way to turn distribution off. Use it when a check should treat a union as one unit.
Too much type-level cleverness
Generic code is read far more often than it is written. A signature with four type parameters, nested conditionals, and several infer positions may be correct but is hard to debug, and its error messages can run to dozens of lines. Prefer these habits:
- Give type parameters meaningful names when there are more than two (
TInput,TOutput), and keep single letters for the obvious cases. - Use built-in utility types (
Partial,Pick,Record,ReturnType) before writing your own mapped or conditional type. - Introduce intermediate type aliases with names, so each step can be hovered and read.
- Write a few usage lines next to a complex type, with the expected result in a comment, so a change that breaks them is visible.
- Keep the public signature simple, even if the implementation needs an assertion internally. Callers see the signature, not the body.
A short decision flow
Summary checklist
| Symptom | Likely cause | Fix |
|---|---|---|
| `T` used once in a signature | Type parameter relates nothing | Use `unknown` or a concrete type |
| `T` only in the return type | Hidden assertion | Return `unknown` and narrow or validate |
| Literal becomes `string` | Inference widening | Constrain `T` to the primitive |
| Error on the second argument | Conflicting candidates | Use a union or two type parameters |
| "Expected 2 type arguments" | No partial lists | Supply all arguments or none |
| "could be instantiated with a different subtype" | Returned the constraint, not `T` | Spread the input or change the return type |
| `as T` in the body | Assertion hides a gap | Pass a factory or redesign |
| `never` result from a conditional | Distribution over `never` | Wrap in `[T] extends [never]` |
Exercise
The function function firstOr<T>(items: T[], fallback: T): T is called as firstOr([1, 2], "none"). TypeScript reports an error. Explain why, then give two ways to make the call compile.
Show answer
T gets candidates number (from the array) and string (from the fallback). They are unrelated, so inference picks one and the other argument is rejected. Fix 1: call it with an explicit union, firstOr<number | string>([1, 2], "none"). Fix 2: change the signature to use two type parameters, function firstOr<T, F>(items: T[], fallback: F): T | F.
Exercise
What does type IsNever<T> = T extends never ? true : false; produce for IsNever<never>, and how do you write a version that returns true?
Show answer
It produces never, because a conditional type over a bare type parameter distributes across the members of the union, and never has no members. The working version wraps both sides in tuples: type IsNever<T> = [T] extends [never] ? true : false;.