TypeScript is a lifesaver, right? It helps catch bugs, makes our code easier to read, and keeps things predictable. But here’s the deal—TypeScript has some sneaky tricks that many developers don’t even know exist. These tricks will not only make your code better but might also make you the “go-to TypeScript guru” on your team. Let’s jump into some cool TypeScript hacks you’ll actually want to use!
1. Conditional Types: The “If-Else” of TypeScript #
Did you know you can make your types behave like decision-makers? Conditional types let you decide the type of something based on a condition.
Example:
Why You’ll Love It:
It’s like giving TypeScript superpowers to adapt on the fly. Perfect for APIs or making flexible utility types.
2. Extract or Exclude Parts of a Union #
Unions are great, but what if you only want a piece of it? TypeScript has your back with Extract and Exclude.
Example:
Why You’ll Love It:
When you’re working with options or enums and need to filter them down, these tools make it ridiculously easy.
3. Infer: Let TypeScript Do the Hard Work #
Think of infer as your personal assistant. It can figure out types for you without you having to spell it all out.
Example:
Why You’ll Love It:
You don’t need to manually write return types anymore—TypeScript handles the detective work for you.
4. Recursive Types: Types for Nested Stuff #
Ever had to work with deeply nested objects? Writing types for those can be a nightmare. Recursive types save the day by letting you define something once and apply it everywhere.
Example:
Why You’ll Love It:
Perfect for APIs or JSON responses where things are all nested and messy.
5. Dynamic Strings with Template Literal Types #
Let’s say you have buttons like “btn-primary” or “btn-danger.” You don’t want to hardcode all these, right? Template literal types let you generate dynamic strings.
Example:
Another example for dynamic strings can be;
Why You’ll Love It:
It keeps your code clean and avoids mistakes—no more typos in CSS class names or dynamic keys.
Practise makes perfect!
That’s it! These tricks might seem small, but they can make a big difference in how clean and powerful your TypeScript code becomes. Happy coding! 🎉