Hacker News new | ask | show | jobs
by anderskaseorg 1655 days ago
JS objects already have runtime types, and you can use them in catch clauses.

    try {
      …
    } catch (e) {
      if (e instanceof FooError) {
        …
      } else if (e instanceof BarError) {
        …
      } else {
        throw e;
      }
    }
There was once a Mozilla extension (https://web.archive.org/web/20200111091805/https://developer...) that allowed you to abbreviate the above to

    try {
      …
    } catch (e if e instanceof FooError) {
      …
    } catch (e if e instanceof BarError) {
      …
    }
It was never standardized, but since it’s just syntactic sugar, if there were demand, it could be standardized without bringing in an entirely new type system.

There would be at least two problems with using TypeScript types for this. Firstly, TypeScript types are unsound in a number of intentional and unintentional ways, meaning that it’s possible for the compile-time and runtime types to disagree, even in fully typed code. Secondly, TypeScript can express many types that cannot be tested at runtime; for example, there is no way to tell whether a function accepts a string as an argument, or to guess the inner type of an empty array.