Hacker News new | ask | show | jobs
by msoad 1655 days ago
Types in TypeScript are great but if JavaScript ever wants to add types it has to be something like a real programming language types in which you can use types in runtime as well. Like in a catch clause I can assert the type of the error and do things with it once that assertion is done. Many other useful things when types space and runtime space are not totally separate.

ES4 was the first shot at adding types to JavaScript which failed due to how big the ambitions were. I'm not sure if there is any more appetite for adding types to JS tho.

In very very serious big applications like a 3D editor you can fall back to WebAssembly and use your favorite typed language. For smaller apps TypeScript is good enough. This way JavaScript stays simple and lean.

4 comments

"real programming language types"

There are a few languages where types only exist (for the most part, though with exceptions and hacks here and there) at compile-time, like Rust, C++ or even Haskell IIRC.

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.

*>...use types [at] runtime..."

Two things. First, TS conceives of itself as having no runtime component. If it did, I think people (including the TS devs) would be more confused.

Second, I'd say rather we need a runtime type system. In fact I've tried my hand at writing one in the most minimalist way possible, and have been working on it recently [1]. The type system is explicit in that a type is a JSON like object, similar to JSON schema, but 100x less code.

[1] https://github.com/javajosh/simpatico/blob/master/friendly.h... This is effectively the test harness for the module.

> it has to be something like a real programming language

It's a nice feature request but there's no one feature that makes a programming language "real".