“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
Taking over Spaghetti Code is every programmer’s nightmare. So that your code doesn’t become someone else’s nightmare, let’s talk about the art of refactoring in TypeScript projects.
1. Reject any, Embrace Types
any is TypeScript’s escape hatch, but if you use it too much, it just becomes AnyScript.
- Bad smell:
function process(data: any) { ... } - Refactor: Even if you don’t know the exact type, please use
unknown, which forces you to perform Type Narrowing before use. Or define aninterface, even if it only has some of the fields.
2. Guard Clauses Instead of Nested ifs
Don’t write “arrowhead” code (nested too deeply).
Bad:
function processUser(user: User) { if (user != null) { if (user.isActive) { if (user.hasCredit) { // Core logic... } } }}Good:
function processUser(user: User) { if (!user || !user.isActive || !user.hasCredit) return;
// Core logic is at the main level, clean and clear}3. Magic Numbers Must Die
Never write if (status === 2) directly in your code. Who knows what 2 means? Is it “Success”? “Failed”? Or “Processing”?
Refactor: Use enum or const constants.
enum OrderStatus { Pending = 0, Processing = 1, Completed = 2}
if (order.status === OrderStatus.Completed) { ... }4. Single Responsibility for Functions
A function should only do one thing.
If you find your function named fetchDataAndProcessAndSave(), it is definitely too long.
- Extract the “fetch data” logic.
- Extract the “process logic”.
- Extract the “save” logic. The main function should just act like a commander calling them.
5. Use Optional Chaining
Bad:
if (user && user.address && user.address.street) { console.log(user.address.street);}Good:
console.log(user?.address?.street);Not only is the code shorter, but the readability is also excellent.
Summary
Good code is like a good article; it reads fluently. Refactoring is not about showing off, but about saving future you (and your colleagues) from losing a few strands of hair.
If this article helped you, please share it with others!
Some information may be outdated





