DEV Community

Jonathan
Jonathan

Posted on

Types vs. assertions

Types are build-time guarantees, assertions are run-time guarantees.

Do we software developers perhaps emphasise the former a little too much and the latter not quite enough?

One way assertions could help is:

Better error messages

Quite often an API call will return some value which we weren't expecting. It will fail with a cryptic message, e.g. about some value not being a valid number. And a mile-long stack trace. It's difficult and annoying to debug these errors.

Imagine if we added an assertion, which would run on the API response, and would report a more developer-friendly error message.

E.g.:

function assertEmployeeIdIsNumber(id: string) {
  if (!isNaN(id)) {
    throw new Exception(
      `Employee id '${id}' is not a valid number."
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Now we can much more quickly & easily pinpoint where in the code this error happened, why it happened, which Backend endpoint caused it and how it could be fixed.

What do you think?

Top comments (0)