TypeScript Code Smells

Common code smells in TypeScript and how to fix them.


Using any

 1// ❌ Bad
 2function process(data: any) {
 3    return data.value;
 4}
 5
 6// ✅ Good
 7interface Data {
 8    value: string;
 9}
10function process(data: Data) {
11    return data.value;
12}

Not Using Optional Chaining

1// ❌ Bad
2const city = user && user.address && user.address.city;
3
4// ✅ Good
5const city = user?.address?.city;

Not Using Nullish Coalescing

1// ❌ Bad
2const value = input || 'default';  // 0, false, '' are replaced
3
4// ✅ Good
5const value = input ?? 'default';  // Only null/undefined replaced

Mutation of Function Parameters

 1// ❌ Bad
 2function addItem(arr: Item[], item: Item) {
 3    arr.push(item);
 4    return arr;
 5}
 6
 7// ✅ Good
 8function addItem(arr: readonly Item[], item: Item): Item[] {
 9    return [...arr, item];
10}

Not Using Union Types

 1// ❌ Bad
 2function handleResponse(success: boolean, data?: any, error?: any) {
 3    if (success) {
 4        return data;
 5    }
 6    throw error;
 7}
 8
 9// ✅ Good
10type Success = { success: true; data: Data };
11type Failure = { success: false; error: Error };
12type Result = Success | Failure;
13
14function handleResponse(result: Result) {
15    if (result.success) {
16        return result.data;
17    }
18    throw result.error;
19}

Related Snippets