DEV Community

Cover image for TypeScript Survival Guide (Part 1): Stop Making These Mistakes
Noriuki
Noriuki

Posted on

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

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.

1. Avoid using any

When I first started using TypeScript, I used any everywhere.

let value: any = "hello"
Enter fullscreen mode Exit fullscreen mode

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.


2. Prefer unknown over any

If you don’t know the type yet, use unknown.

let value: unknown = "hello"
Enter fullscreen mode Exit fullscreen mode

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())
  }
}
Enter fullscreen mode Exit fullscreen mode

This makes your code safer and more predictable.


3. Always type your functions

JavaScript:

function sum(a, b) {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

TypeScript:

function sum(a: number, b: number): number {
  return a + b
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Now anyone can understand your data structure instantly.


5. Learn type narrowing (this is more important than it looks)

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))
  }
}
Enter fullscreen mode Exit fullscreen mode

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.


Final thoughts

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.

Top comments (0)