AI News Hub Logo

AI News Hub

TypeScript Survival Guide (Part 1): Stop Making These Mistakes

DEV Community
Noriuki

If you're coming from JavaScript, TypeScript can feel overwhelming at first. Suddenly, you have types, errors, and things that didnโ€™t exist before. This is a simple survival guide to help you avoid the most common mistakes. any When I first started using TypeScript, I used any everywhere. let value: any = "hello" It works โ€” but it defeats the whole purpose of TypeScript. You're basically going back to plain JavaScript. ๐Ÿ‘‰ Use any only when you really have no other option. unknown over any If you donโ€™t know the type yet, use unknown. let value: unknown = "hello" The difference is: any lets you do anything (no safety) unknown forces you to check the type first Example: function print(value: unknown) { if (typeof value === "string") { console.log(value.toUpperCase()) } } This makes your code safer and more predictable. JavaScript: function sum(a, b) { return a + b } TypeScript: function sum(a: number, b: number): number { return a + b } Now it's clear: what the function expects what it returns 4. Types are not just rules โ€” they are documentation Good types make your code easier to read. type User = { name: string age: number } Now anyone can understand your data structure instantly. TypeScript can "narrow" types based on checks you write. Example: function print(value: string | number) { if (typeof value === "string") { console.log(value.toUpperCase()) } else { console.log(value.toFixed(2)) } } Even though value can be multiple types, TypeScript understands what it is inside each block. This is called type narrowing. ๐Ÿ‘‰ This is what makes TypeScript actually smart โ€” not just strict. TypeScript is not just about avoiding errors. It's about writing clearer, more predictable code. At first, it might feel slower. But once you get used to it, it becomes hard to go back to JavaScript without types.