5 ways to Shoot Yourself in the Foot With Typescript (And What To Do Instead) šŸ”«šŸ¦¶šŸ½

Ndeye Fatou Diop - Jan 15 - - Dev Community

TypeScript is great!

But as a beginner, there are at least 5 ways you can shoot yourself in the foot and end up with a broken app.

Find them below, along with what to do instead šŸ‘‡šŸ½:

Mistake #1: Using any recklessly šŸ˜µ

Using any inadequately removes all the benefits of Typescript.

For example, (a, b) => a+b won't catch bad arguments passed at compile time.

Instead, use the correct types, unknown, or a mixed codebase (Javascript + Typescript).

Mistake #2: Having strictNullChecks turned off šŸ”•

When turned off, the following code will compile fine but fail in production.

function printUser(user: User) {...}
const me = users.find((u) => u.name === "Ndeye Fatou Diop")  
printUser(user) <- This will throw in if an user is not found
Enter fullscreen mode Exit fullscreen mode

So make sure to turn it on.

Mistake #3: Having noUncheckedIndexedAccess turned off šŸ”‡

When turned off, the following code will compile fine but fail in production.

const usersByLocation = {"France": [], "USA": []}
usersByLocation["India"].push(...) <- This will fail
print(usersByLocation["France"][0].name) <- This will fail
Enter fullscreen mode Exit fullscreen mode

So please do yourself a favor and turn it on.

Mistake #4: Using the exclamation mark inappropriately šŸ«¢

Using !, the non-null assertion operator, is rarely a good idea. Your code won't catch when the value is undefined.

Instead, handle null/undefined values properly or rewrite your code.

Mistake #5: Abusing of type assertion šŸ¤„

Using value as MyType is tempting when your code doesn't compile. But, this is risky because the type assertion may be false at runtime, leading to potential UI crashes.

Instead, use this sparingly and only in the relevant context.


That's it šŸ˜

Thank you for reading this post šŸ™, I hope it will help you in your journey!

Leave a comment šŸ“© and add other mistakes you made with TypeScript.

And Don't forget to Drop a "šŸ’–šŸ¦„šŸ”„".

If you like articles like this, join my FREE newsletter, FrontendJoy, or find me on X/Twitter.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .