Don't disable type checks

When you use TypeScript, the goal is to leverage its advantages to the fullest. Selectively disabling TypeScript features defeats this purpose. Surprisingly, there are many ways in which you can disable type checks. But unless you're migrating from a JavaScript project, it's not a good idea.

Can't I just use TypeScript in some places?

To get the most value out of TypeScript, you should be using it throughout your entire project. When certain libraries, functions or other dependencies do not have types, then you have to manually type-check lots of any values which tend to travel through function calls. It makes your code messy, and if you're selectively disabling it in various places it sets a bad example for other collaborators.

So now we'll go through all the possible ways in which you can silence type-checking.

Don't use any

Using the any type means that the value can be anything, and TypeScript will permit any operation on it, including potentially error-prone ones.

// with `any` const value: any = 5; value.toLowercase(); // We allow this breaking bug during compilation // without `any` const value = 5; value.toLowercase(); // Property 'toLowercase' does not exist on type '5'.

Does that mean that you should never use any? Sometimes it's just too easy and quick to resist, especially when prototyping, so it does have its uses. I would argue that it should rarely be used in production code, and if it is, it should be isolated within a function and not "traverse" throughout the code.

Ignore @ts-ignore

The @ts-ignore directive tells TypeScript to not type-check the following line of code. It has its uses in throwaway code and scripts, but should be far away from production code.

Type assertions

In cases where an object's type is unknown or too broad, you might use a type assertion to specify the expected type. This must be done cautiously, as incorrect assertions can introduce bugs.

type User = { name: string; age: number; }; // Type assertions tell TypeScript that an object matches a specific type const x = {} as User; console.log(x.name); // ❌ TypeScript now thinks that `name` is a string, even though it is undefined
// Casting the object as unknown, allows us to assert anything // we want afterwards. const x = 5 as unknown as string; x.toUpperCase(); // TypeScript will allow us to treat x as a string // even though it is a number, leading to a TypeError. // You can get pretty similar results with `as {} as string`

Opinionated type casts may have a place in production code, but you need to be careful. You should only use this form of type assertion when you're sure about the data contained in your variables.

Copyright ©2024 Bestpractices.tech. All rights reserved.