Skip to content

Instantly share code, notes, and snippets.

@gabriel-dehan
Created February 16, 2023 23:05
Show Gist options
  • Save gabriel-dehan/cda8111b7c6b5a8d615fabf6dc2a8374 to your computer and use it in GitHub Desktop.
Save gabriel-dehan/cda8111b7c6b5a8d615fabf6dc2a8374 to your computer and use it in GitHub Desktop.
A case against non-null assertion operator

The non-null assertion operator (!) in TypeScript allows you to assert that a value is not null or undefined, even if the type of the value allows for these values. While the non-null assertion operator can be useful in some situations, abusing it can be dangerous because it can lead to runtime errors and bugs that are difficult to trace. Here are some reasons why the non-null assertion operator can be dangerous if you abuse it:

  • Type safety: Using the non-null assertion operator can bypass TypeScript's type checking and compromise type safety. This can lead to runtime errors when the code is executed, especially if the type assumptions are incorrect.
  • Null pointer exceptions: Using the non-null assertion operator can result in null pointer exceptions if the value is actually null or undefined at runtime. These exceptions can be difficult to debug and can lead to application crashes or unexpected behavior.
  • Maintenance: Using the non-null assertion operator can make code more difficult to maintain and modify over time. If assumptions about the non-null values change, it can be difficult to track down all the places where the non-null assertion operator was used.

Overall, the non-null assertion operator can be a useful tool in some situations, but it should be used judiciously and only when you are certain that the value is not null or undefined. Abusing it can lead to bugs, runtime errors, and maintenance headaches.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment