One long-requested feature for TypeScript is the ability for its types to describe what exceptions a function might throw. "Throw types", as the feature is often called, are used in some programming languages to help ensure developers call functions safely.
The popular strongly typed language Java, for example, implements throw types with a throws
keyword.
Without reading any other code, a developer would infer from the following first line of a positive
function that the function is able to throw a ValueException
:
java
public static void positive(int value) throws ValueException { /* ...*/ }
java
public static void positive(int value) throws ValueException { /* ...*/ }
Throw types are also useful for developer tooling.
They can tell compilers when a function call might throw an exception without safe try
/catch
handling.
That all seems useful, so why doesn't TypeScript include throw types?
In short, doing so wouldn't be feasible for TypeScript -- and some would argue isn't practical in most programming languages. This blog post will dig into the benefits, drawbacks, and general blockers to including throw types in TypeScript. Let's dig in!