Sub topic 14
Common Pitfalls and Good Practice
This chapter assumes you know basic TypeScript types, interfaces, type aliases, functions, unions, arrays, and classes. The goal is to use generics when they preserve a useful relationship between types, not merely to make code look flexible.
Keep Type Information Connected
A generic type parameter is useful when it connects two or more parts of a declaration. For example, T connects the argument and return value:
function firstElement<T>(items: T[]): T | undefined {
return items[0];
}
const numberResult = firstElement([10, 20]); // number | undefined
const textResult = firstElement(["a", "b"]); // string | undefinedThe function returns the same element type that it receives. Replacing T with any would allow unsafe operations and would lose this connection.
A type parameter that appears only once usually adds no value:
function printValue<T>(value: T): void {
console.log(value);
}Here, T does not relate the parameter to another parameter or to the return type. Use unknown instead:
function printValueSafely(value: unknown): void {
console.log(value);
}unknown accepts every value but requires a type check before you use type-specific properties or methods.
Common Errors
| Mistake | Why it causes trouble | Better practice |
|---|---|---|
| Using `any` for convenience | It removes useful type checking | Use a generic or `unknown` |
| Adding an unrelated type parameter | It makes the API harder to understand | Use a concrete type |
| Over-constraining `T` | Valid callers are rejected | Require only needed properties |
| Trusting an assertion | The runtime value may not match the asserted type | Validate external data |
| Supplying every type argument | It duplicates information inference already knows | Let inference work first |
Use Constraints for Real Requirements
A constraint documents what a generic function needs. Keep it as narrow as possible:
function longer<T extends { length: number }>(left: T, right: T): T {
return left.length >= right.length ? left : right;
}
const text = longer("TypeScript", "JS");
const list = longer([1, 2, 3], [4]);
// longer(10, 20); // Error: number has no lengthThe function does not require a string or an array. It requires only a length property. A constraint that says T extends object would be too broad because it would not guarantee that length exists.
Check Keys Safely
When a key and an object must agree, connect them with keyof:
function getProperty<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
const account = { id: 7, name: "Ada", active: true };
const name = getProperty(account, "name"); // string
const active = getProperty(account, "active"); // boolean
// getProperty(account, "email"); // ErrorK extends keyof T restricts the key to actual keys of T. The indexed access type T[K] returns the type of that particular property.
Avoid Inference Traps
TypeScript usually infers type arguments from the call:
function pair<T>(first: T, second: T): [T, T] {
return [first, second];
}
const values = pair(1, 2); // [number, number]
// pair(1, "two"); // ErrorSupply a type argument when inference chooses an unwanted type or when the public API is clearer with an explicit choice. Do not use an assertion merely to silence an error. Assertions change the compiler's view, not the runtime value.
Follow the Type Relationship
Use a generic when it preserves identity, lookup, or structure. Use a normal type when the function accepts unrelated values. When a generic becomes difficult to read, add a constraint or split the operation into smaller functions.
Exercise
Why is getProperty safer than a function that accepts object and string?
Show answer
Its K extends keyof T constraint permits only keys that exist on the object, and T[K] returns the matching property type.