DEV Community

Cover image for Stop misusing TypeScript type assertions
Tim Deschryver for This is Learning

Posted on • Originally published at timdeschryver.dev

Stop misusing TypeScript type assertions

Follow me on Twitter at @tim_deschryver | Subscribe to the Newsletter | Originally published on timdeschryver.dev.


I'm writing this so you don't make the same mistake as our team.
Without knowing how much impact type assertions would have, our team started to use them everywhere.

This started out great.
We had type-safety in our code, and we felt safe to future changes.
At least, we thought so.

In retrospect, we now know that we had created a false sense of security.
We had created a safety net with a lot of holes, which defeats the purpose of having a safety net.

To give a simple example, a lot of our code to create a new instance of a type looked like this.

// inline
const customer = { customerId: newid(), name: 'Sarah' } as Customer;
// or a variant with angle brackets
const customer = <Customer>{ customerId: newid(), name: 'Sarah' };

// even better, via a factory method
function createCustomer(name: string) {
    return { customerId: newid(), names } as Customer;
}
Enter fullscreen mode Exit fullscreen mode

The code has two problems concerning the correctness of these objects when the respective type is changed:

  • new properties that are required aren't caught;
  • existing properties that are removed aren't flagged;

The simple fix is to ditch the type assertions and to replace them with type annotations and return types.

// inline
const customer: Customer = { customerId: newid(), name: 'Sarah' };

// even better, via a factory method
function createCustomer(name: string): Customer {
    return { customerId: newid(), names };
}
Enter fullscreen mode Exit fullscreen mode

With the updated snippet, we now get correct and helpful compile errors when the type is modified.

To enforce this practice, you can enable the ESLint rule Enforces consistent usage of type assertions (consistent-type-assertions).

Fiddle with this example in the following TypeScript playground.


Follow me on Twitter at @tim_deschryver | Subscribe to the Newsletter | Originally published on timdeschryver.dev.

Discussion (5)

Collapse
fiatinnovations profile image
Oyinlola Olasunkanmi

To be honest, I never write type assertions but annotations

Collapse
layzee profile image
Lars Gyrup Brink Nielsen • Edited on

Let me guess, most of you come from C# backgrounds 😃

Collapse
timdeschryver profile image
Tim Deschryver Author

yep... 😅 is it that obvious?

Collapse
jwp profile image
John Peters

Thanks for post.

Collapse
pnminh1710 profile image
Minh Phan

actually when I working with other lib and their type declations is full of any, I have to use this trick to bypass typechecking :D.
FYI: aws-amplify :D