[HN Gopher] A Proposal for Type Syntax in JavaScript
       ___________________________________________________________________
        
       A Proposal for Type Syntax in JavaScript
        
       Author : soheilpro
       Score  : 85 points
       Date   : 2022-03-09 19:07 UTC (3 hours ago)
        
 (HTM) web link (devblogs.microsoft.com)
 (TXT) w3m dump (devblogs.microsoft.com)
        
       | Vinnl wrote:
       | > JavaScript would minimally need to add syntax for things like
       | type annotations on variables and functions (..) however, (..)
       | parameter properties would be out of scope for this proposal
       | 
       | I'm not sure what that last part means, but it doesn't mean that
       | type annotations for function parameters are out of scope, right?
       | 
       | Either way, a big step, congrats to the authors for finding the
       | courage to undertake it!
       | 
       | Edit: no it's not [1], though I'm still not sure what it _does_
       | mean.
       | 
       | [1] https://github.com/giltayar/proposal-types-as-
       | comments#type-...
        
         | uallo wrote:
         | https://www.typescriptlang.org/docs/handbook/2/classes.html#...
        
           | Vinnl wrote:
           | Heh, it's funny how one can have quite a bit of experience
           | with a language, yet remain completely ignorant of parts of
           | it (pretty much everything related to classes, in my case).
           | Thanks!
        
             | replygirl wrote:
             | honestly, if you want an enlightening tour of the language,
             | contemporary angular is the perfect guide
        
       | fulafel wrote:
       | It's been shown I think that keeping JS a simple dynamic compile
       | target has much more value and allows languages compete and
       | evolve separately from browsers. Let us have things like
       | ClojureScript, TypeScript, Elm etc compete & coexist on a level
       | playing field on their own merits.
        
         | runarberg wrote:
         | This proposal is pretty much just adding a standard specialized
         | comment syntax to the language. Different tools can still
         | utilize these comments in their own way. The proposed syntax is
         | pretty on target to what the existing static type analyzers
         | have converged on. I don't see how it is giving an unfair
         | advantage to one tool over another.
         | 
         | If anything it will lower the barrier of entry for new static
         | type analyzers which can compete on how good their type system
         | is, as opposed to the new language they are currently forced to
         | create along side the type system.
        
         | ketzo wrote:
         | The beauty of this proposal is that it would keep JS as exactly
         | that.
         | 
         | Optional type annotations, packaged as a part of vanilla JS
         | instead of requiring a build step, would be the only benefit.
         | They'd be stripped out at runtime; the compiled JS would be
         | identical.
        
       | exclipy wrote:
       | I don't see the point. This proposal only goes halfway and large
       | swathes of syntax (like enums) will not be supported. So it
       | doesn't achieve its stated goal of letting you run Typescript in
       | the browser. The cost is making all JS engines implement the
       | parser, raising the barrier for entry for new JS engines, and
       | hampering innovation in the future by tying Typescript down to
       | the slowest JS engine developer.
       | 
       | The solutions we already have (typescript in comments, or
       | lightweight dev servers like vite) aren't perfect, but they don't
       | come with the gargantuan costs of types in JS.
        
         | neurotrace wrote:
         | For better or for worse, features of TypeScript that generate
         | code (like enums) are generally considered a mistake. I assume
         | part of the idea here is that people would aim to target this
         | particular subset so they can avoid compiling while in
         | development and as such people would move away from those
         | features. I like enums but you can get most of the same
         | benefits with                   type RGB = 'red' | 'green' |
         | 'blue'
        
           | inbx0 wrote:
           | Offtopic but I have to ask now that this came up, why do
           | people even use enums instead of string literal type unions?
           | The latter just seems so much simpler and more readable to
           | me. You get the same type safety, pretty much the same or
           | better performance, autocomplete works fine etc.
           | 
           | One reason I've heard is that enums allow you to do rename
           | symbol refactoring in all use sites, but like what How often
           | do you need to do that? Once in a lifetime? Twice? And with
           | string unions you can ofcourse also just rename it, TS will
           | tell all the places that need fixing, and it'll take couple
           | hours to go though 1000+ usages of it.
        
             | neurotrace wrote:
             | I hear what you're saying but I'd rather not waste even
             | those two hours ;)
             | 
             | I agree with what @erikpukinskis said but I'll also add
             | that I just like the way they read. It immediately tells me
             | that there is a limited number of potential values that can
             | be put in a place. If I see some arbitrary string then I
             | have to wonder, if only briefly, if any arbitrary string
             | can be plugged in there.                   // What does
             | addTask take? Days of the week?         // Time-sensitive
             | identifiers like you'd see in moment.js?         // I guess
             | I'll check the definition or mock out a call to see
             | addTask('Sunday', newTask)              // vs.         //
             | Ah, it takes a day         addTask(Day.Sunday, newTask)
             | 
             | It's subtle and not super important but it makes me happy.
        
             | erikpukinskis wrote:
             | Enums aren't interchangeable, which is either a good thing
             | or a bad thing, depending.
             | 
             | Let's say I have an Icon component with props like:
             | type IconProps = { size: "s" | "m" | "l" }
             | 
             | And then let's say I have a Button component but there's no
             | small size:                   type ButtonProps = { size:
             | "m" | "l" }
             | 
             | If I use string unions I can happy assign one size to
             | another:                   const Button = ({ size }:
             | ButtonProps) => (           <button><Icon size={size} />
             | )
             | 
             | If I used enums (ButtonSize and IconSize) then that would
             | not be possible and TypeScript would complain.
             | 
             | So the question is: Is that a bad thing?
             | 
             | And the answer depends on your domain. If you have reason
             | to believe that in your domain people are likely to map
             | between two incompatible namespaces, then enums could help.
             | And string unions could let through some bugs.
             | 
             | In my experience that's never been a real risk so I prefer
             | string unions.
             | 
             | The other thing enums can get you is you can rename the
             | variable without changing the values. So if your strings
             | are persisted to the database and you don't want to change
             | them, but you do want them to have a slightly new meaning,
             | you could rename the enum key, and get the new name in
             | code, while keeping the old string value.
        
           | throw_m239339 wrote:
           | > For better or for worse, features of TypeScript that
           | generate code (like enums) are generally considered a
           | mistake.
           | 
           | Considered a mistake by whom? they are valid Typescript.
           | 
           | It's just creating yet another flavor of Typescript... and
           | why straight out adopt that type syntax? Because it will
           | please Typescript developers and Microsoft?
           | 
           | All for what? being able to run that flavor of typescript
           | without having to compile typescript files into Javascript?
           | It would change nothing to the already complex build
           | pipelines JS developers are already mandated to use for
           | production.
           | 
           | I agree with the parent, this is a bad proposal.
           | 
           | What Typescript should do as an alternative is better support
           | for JSDoc type analysis. I don't use typescript language,
           | however I do use typescript compiler.
           | 
           | https://www.typescriptlang.org/docs/handbook/jsdoc-
           | supported...
           | 
           | Does it defeat the purpose of typescript? No, typescript is
           | both a language AND a JavaScript static type analyzer.
        
             | neurotrace wrote:
             | > Considered a mistake by whom?
             | 
             | The developers of TypeScript. TypeScript aims to avoid
             | adding anything to the runtime as a result of the type
             | system[1].
             | 
             | > It would change nothing to the already complex build
             | pipelines JS developers are already mandated to use for
             | production.
             | 
             | You're right, it wouldn't change anything when you're
             | building for production if you're doing things right. It
             | would mean that you don't have to repeatedly compile your
             | code while you're developing it though.
             | 
             | > What Typescript should do as an alternative is better
             | support for JSDoc type analysis.
             | 
             | If you read the proposal you'll see they explain why
             | expanding JSDoc is not ideal. Personally, I wrote a lot of
             | JSDoc back before TypeScript and now I don't want to touch
             | the stuff. TS is much more ergonomic and expressive.
             | 
             | [1]:
             | https://github.com/Microsoft/TypeScript/wiki/TypeScript-
             | Desi...
        
         | ketzo wrote:
         | > So it doesn't achieve its stated goal of letting you run
         | Typescript in the browser.
         | 
         | At risk of running afoul of HN guidelines: did you actually
         | read the post?
         | 
         | The proposal does not add type _checking_ to JavaScript. It
         | adds _type syntax_. There is a huge, huge difference.
         | 
         | Their proposal is to implement a comment-like type syntax.
         | These types would be totally ignored at runtime.
         | 
         | This isn't "run TypeScript in the browser"; this is "add
         | syntactic sugar to vanilla JavaScript to get the development
         | benefits of types without a build step."
         | 
         | Yes, JavaScript engines would have to implement a parser for
         | this syntax. Yes, this raises the barrier to building a new
         | JavaScript engine.
         | 
         | Does that mean JavaScript should add _no new syntax ever
         | again?_ No, of course not. So the question becomes one of cost-
         | benefit analysis. And I think the TS team has submitted an
         | extremely compelling argument for the benefits.
         | 
         | Your comment acknowledges the existing benefits of types-in-
         | comments; think of this proposal as a significantly nicer way
         | to write those.
        
       | brianleroux wrote:
       | FINALLY, both Ruby and Python have had optional types for a
       | while; glad JS is catching up.
        
         | fooyc wrote:
         | PHP has optional types as well, although types are enforced
         | when present
        
           | colejohnson66 wrote:
           | That's a major limitation of JavaScript. For example:
           | // TypeScript         function add(a: number, b: number):
           | number { return a + b; }              // tsc output
           | (JavaScript)         function add(a, b) { return a + b; }
           | // (ab)use by someone using my lib without TypeScript
           | add("abc", "def");
           | 
           | Now, addition is a contrived example because it'll still work
           | with strings, but the point is that such usage violates my
           | code contract because _the contract was deleted during
           | compilation._ It 's possible to do this:
           | function add(a: number, b: number): number {             if
           | (typeof a !== 'number' || typeof b !== 'number')
           | throw 'no';             return a + b;         }
           | 
           | But that's needlessly verbose, and eslint will complain about
           | useless code. If enforceable type annotations could be added
           | to JavaScript, that'd be a huge plus.
        
             | ketzo wrote:
             | As I understand this proposal, it would not add what you're
             | talking about. Just for clarity.
        
           | [deleted]
        
       | throw_m239339 wrote:
       | This proposal is essentially a way to standardize a subset of
       | typescript (a subset for now...).
       | 
       | It's Microsoft imposing their technology on the ECMA committee.
       | 
       | Ironically the same Microsoft that rejected ES4. We wouldn't be
       | needing Typescript if ES4 was adopted 15 years ago...
       | 
       | edit: While this proposal doesn't have runtime typechecks, it's
       | just one step toward adding runtime typechecks it isn't a stretch
       | to think that if this passes, runtime typechecks might eventually
       | be added to the language. ActionScript 3/JScript.net/ES4 had
       | them, so it's perfectly possible for Javascript "with types" to
       | add them as well.
        
         | DanRosenwasser wrote:
         | Hey there, speaking as a champion of the proposal, the
         | TypeScript PM, and a representative in TC39 for 6 years, we're
         | not trying to impose anything or pressure anyone. We hope to
         | present this proposal, and are fully open to discussion and
         | criticism. We are committed to working with other standards
         | representatives, working through the stage process, and not
         | "pushing weight" around here.
         | 
         | I wasn't there for ES4; however, the type semantics of ES4 is a
         | drastically differ from what's being proposed here. There is
         | some information on the FAQ about why runtime types are a non-
         | starter. (https://github.com/giltayar/proposal-types-as-
         | comments/#why-...)
         | 
         | This comment probably won't count for much - actions speak
         | louder than words. Hopefully we can demonstrate that we're
         | being genuine here.
        
       | jiripospisil wrote:
       | Why not support TypeScript natively in browsers instead?
        
         | robpalmer wrote:
         | The FAQ addresses this:
         | 
         | https://github.com/giltayar/proposal-types-as-comments#shoul...
         | 
         | https://github.com/giltayar/proposal-types-as-comments#shoul...
         | 
         | The idea is to avoid hampering competition, evolution, and
         | innovation in the type-checking space.
        
         | dfabulich wrote:
         | https://github.com/giltayar/proposal-types-as-comments/#why-...
         | 
         | > _Why not define a type system for JS in TC39 instead?_
         | 
         | > _TC39 has a tradition of programming language design which
         | favors local, sound checks. By contrast, TypeScript 's model --
         | which has been highly successful for JS developers -- is around
         | non-local, best-effort checks. TypeScript-style systems are
         | expensive to check at application startup, and would be
         | redundant every time you run your JavaScript applications._
         | 
         | > _Additionally, defining a type system to run directly in the
         | browser means that improved type analyses would become breaking
         | changes for the users of JavaScript applications, rather than
         | for developers. This would [violate goals around web
         | compatibility (i.e. "don't break the web")][1], so type system
         | innovation would become near-impossible. Allowing other type
         | systems to analyze code separately provides developers with
         | choice, innovation, and freedom for developers to opt-out of
         | checking at any time._
         | 
         | > _In contrast, trying to add a full type system to JavaScript
         | would be an enormous multi-year effort that would likely never
         | reach consensus. This proposal recognizes that fact, and also
         | recognizes that the community has evolved type systems that it
         | is already happy with._
         | 
         | [1] https://github.com/tc39/how-we-
         | work/blob/cc47a79340a773876cb...
        
           | [deleted]
        
         | [deleted]
        
         | Gaelan wrote:
         | This is essentially doing that--it would allow browsers to
         | parse and run TypeScript. What it isn't doing is actually
         | having browsers do type checking, for good reason: the
         | TypeScript type checker is a large and complex piece of
         | software, so browsers would either have to incorporate it (and
         | they're probably not excited to have a large chunk of JS code
         | in the critical web-page-rendering path, nor would they be
         | excited to have a critical chunk of the browser with a single
         | implementation), or reimplement it themselves (which would be a
         | huge amount of work, and make changes to the language much
         | slower and more difficult).
        
           | adamddev1 wrote:
           | Ya this seems like an awesome idea. Let devs run the type
           | checking before they ship code, and then let the browsers run
           | the code just as they would plain JavaScript, ignoring the
           | types. If someone's going to use TypeScript they would be tye
           | checking it first anyway, so no real need to check it again
           | at the browser.
        
       | armchairhacker wrote:
       | why not just make JavaScript engines like node and browsers strip
       | out TypeScript? Hide it under a flag if you want, it's developers
       | who are debugging who would benefit from that the most.
       | 
       | I mean this is a great idea, removing one more of the many many
       | complexities in simply getting a nodejs package to browser and
       | debugging (getting accurate source info and avoiding transpile
       | errors are a PITA). JavaScript is an interpreted language yet 90%
       | of the time it's not even run interpreted. But "a proposal for
       | Type Syntax in JavaScript" when TypeScript _and_ JSDoc exist is
       | just confusing and redundant.
        
         | MBCook wrote:
         | But isn't that what this is? Just an agreed upon way of
         | specifying type info so browsers can be taught to ignore it
         | instead of having to strip it at build time to produce
         | something the browsers can parse?
        
           | ketzo wrote:
           | Yes. That's literally what this is. I'm not actually sure
           | what the OP is saying.
        
       | atom_arranger wrote:
       | IMO MS should focus on making tsc faster, browsers shouldn't have
       | this added complexity for no benefit. This would also seem to
       | encourage shipping extra non-functional code to users. If the
       | only benefit is in development then that could just be served by
       | sourcemaps.
        
         | dfabulich wrote:
         | This is "making tsc faster," by allowing developers not to run
         | it. You can't get faster than that!
        
         | replygirl wrote:
         | one potential benefit here is developing in your target
         | environment, which currently almost none of us are
        
       | eyelidlessness wrote:
       | On its face this is (to me) an obvious, and obviously good,
       | proposal _in the abstract_. So obvious I'm astonished it's taken
       | so long to materialize. I'll leave it to the proposal and other
       | advocacy to justify that: I'm just noting my bias for anyone who
       | may misinterpret what follows, because I have _some concerns_
       | about the details.
       | 
       | 1. While care was obviously taken to be type system agnostic, and
       | while TypeScript is obviously the current incumbent, I think
       | there could be more of a sign of _collaboration_ with Flow,
       | Closure and Hegel.
       | 
       | 1a. They're notably mentioned but conspicuously no one from those
       | projects is listed as authors/champions. This suggests to me that
       | they weren't (substantially) consulted in drafting the proposal,
       | which implicitly weights the proposal's _details_ in TypeScript's
       | favor if only by inertia.
       | 
       | 1b. There's surprisingly little "give" in terms of the few minor
       | differences between Flow and TypeScript. I'll grant the potential
       | reservation of `opaque type`, but strongly suspect that's because
       | opaque types are already under consideration as a TS feature.
       | 
       | 2. Omission of certain runtime-affecting constructs is certainly
       | pragmatic, and not omitting them almost certainly a deal breaker
       | for the proposal. But, it's also quite likely to fragment
       | TypeScript, effectively deprecating those parts of the language
       | (which I'm sure the TS team would prefer to do explicitly, but
       | well, that's a much heavier lift).
       | 
       | 3. This limited subset of TS syntax _almost certainly is_ a real
       | superset of JS, but there are some parsing disambiguation
       | complexities to consider, particularly for type parameters on
       | functions as well as (if ultimately included) function overloads
       | and bare property modifiers. This also affects runtime
       | performance, particularly at load time which is critical.
       | 
       | 4. Omitting JSX makes sense _in the current state of the world_ ,
       | but does it make sense for the goals of this proposal?
       | 
       | 4a. JSX usage _outside of TS_ has an almost totally overlapping
       | motivating problem: the need for a build step. It doesn't fit the
       | proposal _now_ , because JSX (usually) has runtime semantics, but
       | they're unspecified without build time configuration.
       | 
       | 4b. Of all things that will fracture TS, this one is
       | irreconcilable. I'm honestly surprised it's even being considered
       | by anyone on the TS team.
       | 
       | 4 (conclusion). Given 4a/4b, JSX almost certainly should be a
       | separate proposal, but I think it should seriously be considered
       | as a potential prerequisite.
       | 
       | 5. The goal of rapidly evolving TS and conservatively evolving
       | TC39 is a balance that probably can be struck, mainly because the
       | TS team has been incredibly good at keeping their syntax and
       | semantics aligned with standards. But baking type comments into
       | the language with a variety of new syntax blocks that syntax from
       | being used for other proposals. For type-only syntax that's
       | obviously not a huge deal, but I'm imagining a fair bit of push
       | back on reserving, say, the colon character in function
       | positional arguments.
       | 
       | Probably more I haven't thought of. And I want to reiterate I
       | think this is a great idea in the abstract. I want to see it
       | succeed. If the champions or any of the TS/Flow/Closure/Hegel
       | teams, or anyone else here thinks any (or all) of these concerns
       | should find their way into issues on the proposal repo, please
       | feel free to copypasta or ask me to do same.
        
       | [deleted]
        
       ___________________________________________________________________
       (page generated 2022-03-09 23:01 UTC)