tc39 / proposal-type-annotations

ECMAScript proposal for type syntax that is erased - Stage 1
https://tc39.es/proposal-type-annotations/
4.13k stars 44 forks source link

Why can't this feature do type checking at runtime? #205

Open DonaldDuck313 opened 6 months ago

DonaldDuck313 commented 6 months ago

According to the description of this proposal,

At runtime, a JavaScript engine ignores [type annotations], treating the types as comments.

I think it would be better if type checking were done at runtime. To be clear, I suggest that the type checking should be done when running the actual code similar to what is done in PHP, not when parsing it similar to what is done in TypeScript. So for example I suggest that this:

function f(x: string){
    //Function body
}

should do roughly the same thing as this:

function f(x){
    if(typeof x != "string"){
        throw TypeError("Expected parameter x to be a string, got " + x?.constructor?.name);
    }
    //Function body
}

You mention in your FAQ that

Implementing this proposal means that we can add type systems to this list of "things that don't need transpilation anymore" and bring us closer to a world where transpilation is optional and not a necessity.

While this is true for transpilation, if type checking isn't done at runtime as you suggest, the code will still have to be run through static type checkers. If type checking were done at runtime, however, it would allow to run the code directly in the browser in a type safe way without using any third-party tools to analyze it at all.

Is there any reason why you decided not to do this?

tabatkins commented 6 months ago

In short, it was decided against because it would mean that JS is responsible for defining and maintaining a type system. It looks simple enough with simple cases, like "x: string", but then you get into subclasses, generics, covariant and contravariant type variables, type functions, etc. It's a huge undertaking, much larger than just allowing the annotations themselves, and it would mean that the type system also ends up with the same back-compat constraints as the rest of JS, rather than allowing tools to experiment and upgrade over time.