17 ms·
First look: adding type annotations to JavaScript
- montroser 5y agoI would welcome this making its way into ECMAScript not because I like TypeScript, but because it's a drag to see TypeScript enthusiasts litter the JavaScript ecosystem with all of the piles of bolt-on TypeScript baggage. Forking projects just to add type definitions, or else mega repos like DefinitelyTyped madness; bringing all of the terrible complexity that we love to hate in Webpack/ESBuild/Rollup/etc back over to Node.js with server-side tsc; drive-by PRs to all my open source projects from inspired people trying to add types and me having to disappoint... I would gladly do without all of that. To me, I see the TypeScript tradeoff as coming with only marginal upside, in return for a large downside as described above. But, others passionately disagree and see a huge upside, and that's cool. In the end, I want us all to be happy, and I think this proposal would have hope getting us there. For this to be really spec'd and standardized would be a green light even for skeptics to invest in deeply learning and internalizing. To get to avoid yet another build-time compilation step would be bliss. To have us all back in on the same team would be glorious.
- IshKebab 5y agoYou're wrong - the benefits of Typescript are huge, and the size of the hoops people are willing to jump through to get those benefits should indicate how big they are. I do agree it would be nice to simplify some of the tooling though.
- ht85 5y agoDo you write a lot of library code? I'm genuinely wondering in what kind of environment you would get "marginal upside" from having a good type system.
- riskable 5y agoI've been coding JavaScript for many, many years. I've never encountered a situation where the lack of typing bit me in the ass. Not even once! Having said that, it might be because when I'm writing JavaScript it's just me. Normally I'm the sole developer. So of course I know my own stuff! I'm not going to experience an error passing the wrong type to a function because I literally wrote all the functions myself. I even have enormous libraries of JS code that I use in my personal and work projects where I wrote everything. This developer is probably in the same sort of situation. Type errors are the kind of thing you run into when you're working with large codebases that were written by lots of different people. It's not the type of thing you experience with your own code. I've also written loads of Python and never experienced an error where the wrong type gets passed to a function (even working in a team). For years I couldn't even fathom how static typing would be a benefit other than maybe it can speed things up by giving a compiler/interpreter the ability to optimize things. Then at work--after nearly 20 years of Python--we finally had an issue where the wrong type was passed (float was inadvertently rounded because the function was made for integers and it wasn't obvious). It was caught before the code was sent to production (and it wouldn't have been a huge deal anyway) and I finally had a real-world situation where type annotations would've prevented an error. It's just not something that happens very often. It's the type of thing that creeps up on you for sure but it's not a common, every day occurrence. Type-related bugs are really super obscure. They're far, far rarer than type-obsessed developers make them out to be.
- Turing_Machine 5y agoI've often speculated that strong typing only seems like a win to the kind of developer who makes a lot of type errors, and a waste of time to those who don't (which doesn't mean they don't make other errors, of course).
- Aldo_MX 5y agoOr to the kind of developer that works in a big team for a big project.
- markstos 5y agoEven developers who "don't make type errors" have to deal with bad and unexpected data, which may be in a different type. If you don't validate that all untrusted data is off the appropriate type, security vulns or "garbage in - garbage out" bugs can result. Then if you do manually validate the types of untrusted data, then you have to wonder of having built-in type support might be faster. "Bad data" doesn't just come from the outside world. As teams start to use shared libraries written by other people, it's also valuable adds guards to ensure that shared functions are being called with the expected types. My own experience is that it doesn't feel like type-related bugs come up often on my team, but when they do the problems they cause can be bad enough to make us wish more of our code had been ported to TypeScript. Classic example: a CSV parser parsed numbers as strings because a particular spreadsheet quoted the number column. Result: "2"+"2" = "22"
- rattlesnakedave 5y agobringing in tooling to eliminate an entire class of potential errors sounds sounds like an easy decision to me.
- Turing_Machine 5y agoNot if the errors are rare and the "tooling" slows down development.
- 5y ago
- Waterluvian 5y agoI used to feel the same way about TypeScript until I really gave it a try one season. I feel like I was crippling myself for years, being an inferior developer wasting so much time with the things that TS guards against, documents, and autocompletes for. I support any formalization of TypeScript that further tidies up the "add-on" nature of it. But to be honest, it's really quite fine already.
- edgyquant 5y agoI work at a place that is full stack typescript with a legacy app that is Js/react (the kind of stuff I was writing in 2017-2018.) After using typescript and going back to fix issues on the legacy codebase I now understand why the industry adopted Ts
- seniorsassycat 5y agoWould you use type comments in your projects? Would you like pull requests adding them, or fixing them? What if the typescript checker and another checker have different semantics and you have fans fighting between `number` and `u8`?
- keawade 5y agoI disagree that TypeScript comes with only a marginal upside. In my experience TypeScript projects are much more approachable for contributors. For example, I once was debugging an issue in a JS framework and while I knew what was wrong and where I could fix it I didn’t have any idea what existing tools I had available in that context to fix it. Having type definitions would have made that work much simpler by increasing the accessibility of the code base. It’s experiences like this that have convinced me that if I’m writing code that any one will possibly read or need to modify later (including if it is just me) then I should be writing TypeScript instead of JavaScript. Or, more generally, that it should be typed.
- shadowgovt 5y agoYou and OP are both right, because it really depends on what you're doing. At the scale I operate, it would be corporate suicide to try and write this code in straight JavaScript without type support. But for smaller teams, more focused teams, and teams that use a heavy testing discipline or enforced naming conventions that supplement the lack of static typing, it's not a problem.
- NoWizards 5y agoI couldn't disagree more with you... All i see when working with different levels of experienced contributors is param:any any[]. Even more when you want to interact directly with DOM instead of using an opinionated framework.
- selfmodruntime 5y agoYou‘re blaming the active misuse of a tool on the tool itself.
- david422 5y agoThis is either just code that is too complicated or devs that aren't doing a good job of type hinting. Everytime there is an any, it means that each developer reading or modifying this code has to find it out for themselves - every single time. Why not just type hint it correctly in the first place.
- spion 5y agoThis isn't going to fix those issues. Those issues aren't due to tsc. They're due to an ecosystem which refuses to recognize the realities of compilation and add first class support for it. Its also due to an ecosystem willing to break compatibility (and not just backward compatibility but compatibility to other tools) at the drop of a hat. For example, the main reason I've seen why people began using bundlers for node recently is the fact that a lot of modules transitioned to pure ES6 without CommonJS support. In most projects, this means you have to use a bundler to be able to import those modules, or switch your entire codebase to ES6 (which is non-trivial due to changes in import path semantics). If it weren't for the above, you could just run `tsc` to get a `.js` file in `dist` for every `.ts.` file in `src` and run node on those.
- afavour 5y ago> They're due to an ecosystem which refuses to recoginze the realities of compilation and add first class support for it. IMO this is the correct path. Compilation should result in WebAssembly and it seems like the tooling is finally getting there.
- dmitriid 5y ago> Compilation should result in WebAssembly It... It really shouldn't. Especially not if the target is the browser as the bridge between WebAssembly and the rest of the browser is still "just pass these arrays of integers around".
- jeremyjh 5y agoI do not think that is a goal of either project; I’m not even aware of a POC JavaScript to WASM compiler. AssemblyScript couldn’t work without strong typing semantics and doesn’t support many typescript features.
- spion 5y agoOf course, using a bundler means you'll face several other unpleasant realities. Like - what about tests, how do they run - source maps support in node being 3rd party and unbearably slow for any medium sized project - edit: this has been fixed somewhat recently https://nodejs.medium.com/source-maps-in-node-js-482872b56116 - only the 3rd party bit, not the slowness bit https://github.com/nodejs/node/issues/41541 - also applicable when not bundling, albiet fewer reprcutions to turning off source maps - poor native (C++) modules support in bundlers - modules with really dynamic `require` statements being supported at varying levels by varying bundlers
- afavour 5y agoFor what it’s worth I agree with you: after spending years battling with Babel and all that nonsense it’s been amazing to be able to just write ESM JS and have it run both on Node and in the browser. The real lightbulb moment for me was using JSDoc annotations with TypeScript types in JS files. It definitely isn’t as graceful as JS itself but it’s not that big of a deal, plus it encourages you to add comments. And any TypeScript editor will parse the code as if it’s TS, provide autocomplete, type checking etc etc as required.
- simion314 5y agoJust finished debugging one of those ugly issues where it works fine for the developer but for some other person things are broken. it was a piece of code that assigned an Number to a property that should have been an object(the dev confused the property name). Because the project is complex and there is a lot of network requests and stuff running in different order depending on the user internet the bug did not happened to everybody. You could work aroudn this using setters and doing runtime checks but I have a feeling people that don't like types also don't like getter and setter.
- markstos 5y agoAre you saying that if there had been type checking, this issue would have been much easier to detect and prevent?
- jaywalk 5y agoHow could it not be? With type checking, you wouldn't be able to set a variable to a number when it's supposed to be an object.
- simion314 5y agoYes a line like stuff.anAccountTypeField = obj.aNumberValue; Would cause an error in a typed language , something like incompatible type Number and type Account. Maybe you were confused by my commnet about the network requests and different order of running code, this caused the error not to happen most of the time so it never crashed on developer machine.
- dlojudice 5y ago> To me, I see the TypeScript tradeoff as coming with only marginal upside, in return for a large downside as described above. I've coded using static and dynamic types. C#, Java, Ruby, JS, etc. 20 something years doing it, mainly for business applications (opposed to system or embedded). My personal opinion is that types bring an elusive value of control and maintainability. Confronted with legacy / spaghetti code, developers with less experience will bring lint, code style, some layers and ... types, as a way to solve the problem of long term maintainability. But unfortunately it does not bring that much value. Actually it brings costs to readability and unnecessary abstraction (interfaces, generics, etc) aka "fighting the compiler". A better test suite can have exponential more value on maintainability than types. > Static Typing was the most requested language feature in the State of JS survey in both 2020 and 2021. [1] So when I see static types been the most requested feature I wonder how many of them know how to create a good test suit or a good architecture. If its behind this feature request is a different pain to be solved. [1] https://github.com/giltayar/proposal-types-as-comments/#community-usage-and-demand https://github.com/giltayar/proposal-types-as-comments/#comm...
- azangru 5y ago> A better test suite can have exponential more value on maintainability than types. A lot of ink has been spilled over this question. The conclusion is: no, tests do not and cannot replace types. Types, in themselves, provide a layer of tests that nobody, typically, would think of writing (what if a function is called with fewer arguments? what if it receives a different type of argument from what it was expecting?) and eliminate a whole class of superfluous tests that are checking for things that are better checked with types. The self-documenting property of types is remarkable. Jsdocs do not hold a candle to a typed codebase. Plus, refactoring. Even with tests I would be scared of large refactorings if I didn't have a type checker to also hold my hand. Of course, maybe I just don't know how to write code properly.
- kemiller2002 5y agoI always say that Types are not there for the truly expert programmer. They are there for the rest of us. It's a lot easier to pick up code and understand it when you at least have an inkling as to what a variable or parameters needs to have to function. Can interfaces be confusing, and generics become difficult to read? Yeah of course, but that's not really the problem of static type system, that's a problem with the code. I've generally found if you're doing something where you're thinking "this is just getting the way", you probably need to rethink your approach. Clear is always better than clever.
- kingdomcome50 5y agoFound the guy who hasn't used Typescript beyond tinkering! I kid... mostly. But in all honesty I have found very few instances of developers who have worked significantly with both languages and have come to the conclusion that TS has a marginal upside (though maybe they will come out in defense here!).
- claytongulick 5y ago<raises hand> I've worked extensively with both. I find that ts normally brings a downside, actually. In one project I maintain, a solid 30% of the code is nothing but ts stuff. It makes maintaining the code base excruciating. Small changes between versions of ts or .d.ts files have caused hundreds of errors. A concrete example of this is the change in mongo driver that forced "new ObjectId()" instead of "ObjectId()" though functionally there was no difference. I see massive bizarre and difficult to grok type declarations that grow in excruciatingly byzantine complexity just to satisfy the compiler for non-trivial flexible function definitions. I see painful compilation times, a beefy laptop's CPU getting pegged and the fan whining while trying to do even minor updates. Try to do a build while on a video conference? I see two to three minute build times. I see a series of nonsense stories in sprints that are nothing more than activity over achievement. They don't drive product functionality, they are a bunch of make-work to satisfy the developer asthetic and the compiler. The nightmare of "compiled" NodeJS production support is a dystopian hellscape that I'm forced to endure every day because of NestJS and typescript. And nothing in that has done anything to increase code quality or reduce bugs from the crappy offshore team that wrote it. Clearly, I'm not a fan. That being said, I think type comments in jsdoc are a honking good idea. I use inline /* @type */ declarations and .d.ts files liberally. If we could add to jsdoc the ability to document types and purpose of arbitrary js objects inline, at definition time, instead of an external .d.ts file, I'd be a happy guy. An example of this would be sequelize schema defs, or mongoose schema defs, where I can have all my jsdoc code comments and type definitions in the same place as the code. All that being said, I like the idea of this proposal. Especially if it could solve the schema definition issue above. I think optional typing is a good idea to bake directly into the language. I thought AS3 did a great job of this. I even think it would be great to have an equivalent of "strict" that would enforce typing at the module level to enable straightforward AOT / wasm interop (I know it doesn't solve the GC issue). My beef is mostly with the extra compilation step and needless complexity of ts. If we had simple (no generics) opt-in typing that was natively supported by the engine, I think it would enhance the language overall, like type hints have done for python.
- yboris 5y agoYou should try Vite - https://vitejs.dev/ https://vitejs.dev/ - start a TypeScript project in under a minute - no annoying Webpack configuration needed.
- fifticon 5y agoI abandoned my attempts to make larger projects in pure javascript. I happily write larger projects in typescript. Typescript makes javascript feasible, usable for me.
- rvieira 5y agoAs someone who doesn't really work with neither JS or TS, the proposed JS type system looks superficially very similar to TS. Is this "backporting" TS to JS or is there something else I'm missing?
- icholy 5y agoIt's the TS team making the proposal.
- idontknowifican 5y agothis is common in ECMAScript. see coffeescript and arrow functions
- jayrhynas 5y agoAs far as I understand it, this is allowing TS types to be valid JS syntax that are just ignored by vanilla JS engines. So it is intentionally identical to TS, it just won’t have any affect on the execution of your code.
- Ndymium 5y agoIt's not identical as features that have a difference on the runtime behaviour / code generation such as enums are deliberately omitted. It's intended to be a large subset of TS at first. [0] [0] https://devblogs.microsoft.com/typescript/a-proposal-for-type-syntax-in-javascript/ https://devblogs.microsoft.com/typescript/a-proposal-for-typ...
- nerdponx 5y agoFor perspective, this is more or less what Python did. Originally Mypy was supposed to be a Python superset, like TypeScript, but instead its variable annotation syntax was adopted as Python syntax. It has been an interesting journey for Python, with a lot of ups and downs. Type hints, for all their productivity and bug-safety benefits in most cases, still feel like a bolt-on feature that requires developers to change how they write code, and in many cases favors less-performant idioms and/or extra boilerplate compared to un-hinted Python. Whereas TypeScript has a lot more freedom to mess with how things work, because it's a superset that compiles to JavaScript and not actual JavaScript. So it's somewhat surprising to see this proposal for JavaScript, because the TypeScript model always seemed better in hindsight than the Python model! But maybe it's just a "grass is greener" situation.
- deleted 5y ago[deleted]
- ape4 5y agoIs there a way to say a variable can hold any type - eg for a log or print function.
- kevingadd 5y agoThat's the default
- Ndymium 5y agoTypeScript itself has two types for this purpose: "any" and "unknown". "any" is the escape hatch and allows you to do anything with the variable. In essence it stops type checking entirely for that variable. "unknown" takes the opposite approach and doesn't let you do anything with the variable value (other than pass it along to other "unknown" accepting variables/functions) until you have asserted its actual type with type guards.
- deleted 5y ago[deleted]
- Cthulhu_ 5y agoI'm more and more thinking that JS is heading in the wrong direction. I'd opt for splitting up JS into two; one is a low level compilation target, something like... I forgot the name now, it was a subset of JS with hints in comments that allowed the interpreter to forego certain checks (mostly around the dynamic nature of e.g. objects) for speed, I believe this predated WASM and co. Anyway, a simple version of JS or more like bytecode. Then developers can pick whichever language they want. Because these type annotations do not benefit execution, only development.
- assbuttbuttass 5y agoIsn't WASM basically this low level compilation target you're talking about?
- xmorse 5y agoBefore wasm there was asm.js [0] [0] https://en.wikipedia.org/wiki/Asm.js https://en.wikipedia.org/wiki/Asm.js
- leodriesch 5y agoI’d say WASM is the low level compilation target for JavaScript runtimes. There is also a proposal for directly shipping ASTs instead of JavaScript source files for performance improvements [0]. [0]: https://github.com/tc39/proposal-binary-ast https://github.com/tc39/proposal-binary-ast
- nerdponx 5y ago> Because these type annotations do not benefit execution, only development. Well this is why TypeScript was invented in the first place. Not to mention that "static-only" type annotations are being adopted in Python and Ruby as well. Clearly a lot of developers see a lot of value in them.
- isaacimagine 5y agoYou're thinking of asm.js: http://asmjs.org/faq.html http://asmjs.org/faq.html
- 5y ago
- IceHegel 5y agoHere’s why I support this: I want to write, run, and debug a js file in node without intermediate files. Repl speed would increase a lot.
- synergy20 5y agoEven better, make sure browsers typescript ready or fully compatible over time. In my opinion Typescript and Javascript should merge into one and gradually shift towards Typescript. I used to feel TS is just extra effort unneeded, after using it for a while, I found it so great I no longer want to code in JS, not at all.
- chess_buster 5y agoMe, too.
- madeofpalk 5y agoThe MS blog post, and actual proposal covers this fairly well imho: Typescript's type checking is slow and doesn't need to happen at runtime. Additionally, it moves failures to users rather than developers and makes it incredibly difficult to change type semantics later on. https://devblogs.microsoft.com/typescript/a-proposal-for-type-syntax-in-javascript/ https://devblogs.microsoft.com/typescript/a-proposal-for-typ... https://github.com/giltayar/proposal-types-as-comments/ https://github.com/giltayar/proposal-types-as-comments/
- xmorse 5y agoIt would be cool to have this, but i think that adding so many features at once to the language isn't going to happen, and adding one piece at a time doesn't make sense. Also, the parser performance will probably take a hit.
- KaoruAoiShiho 5y agoDon't think this should affect performance, so it's a win for devs at no cost to the execution. Should just be a good thing no?
- cphoover 5y agoStop trying to make JavaScript into something it's not... If you want a type system Typescript works great, and it's very easy to set up. You even get debugging to the original uncompiled source with sourcemaps. If you want a strongly-typed static language, compile to a wasm target... That's what it is for. Stop trying to change JavaScript into a language it is not. JMHO
- halfmatthalfcat 5y agoI mean, with all due respect, who are you to decide what Javascript is and is not? There's obviously a huge demand for type safety in Javascript, hence the existence and adoption of Typescript.
- Turing_Machine 5y agoCompare the lines of code (on Github, say) written in straight Javascript and the lines of code written in Typescript. I do not think the demand is quite as huge as you think it is.
- rattlesnakedave 5y agoI'm not sure that's a useful metric.
- Aldo_MX 5y agoThis is like saying compare the lines using generators or proxies vs the lines using type annotations. Just because a feature is not widely adopted it doesn't mean that is not useful to the people using it, especially when the feature is used to mitigate the entire "cannot find property of undefined" type of errors.
- latortuga 5y agoIn the linked article, the author spends 1 sentence dealing with objections: > I can understand if JavaScript developers are afraid of TypeScript taking over their language. However, this proposal will be as far as things will go w.r.t. adding TypeScript features to JavaScript And in the next few sections it includes someone who wants to build on the proposal including using type hints to optimize code. I just think there's literally no way to guarantee that "this will be as far as things will go". Yes languages evolve and add new things all the time. But GP's point is that the language seems to be going toward what people want it to be coming from other languages. I agree, stop trying to make JS something it's not.
- mbf 5y agoErasable types are good enough with source mapping. TypeScript workflows are fine. ECMAScript really doesn't need to absorb a TypeScript syntax. It's not necessary to keep bloating the runtime with a feature only useful to the developer.
- eminence32 5y agoIf the runtime is going to be fully ignoring these type annotations, what type of "bloat" are you worried about?
- windows2020 5y agoNew syntax and concepts.
- xigoi 5y agoLarger file sizes.
- cphoover 5y agolarger downloads, larger syntax
- seniorsassycat 5y agoMicrosoft should add script/typescript support to edge with a checkTypes flag /s
- l30n4da5 5y agoIm curious what a proposal like this means for other compile-to-js languages. I'm assuming it really won't make any difference to those, but languages like ReScript, PureScript, or Elm, for example, all are statically typed and compile to js in the end.
- jakelazaroff 5y agoI don’t think it means anything, since the JS parser will just ignore the type annotations.
- l30n4da5 5y agothat was my thought, as well. curious to see, though, if popularity of other statically-typed compile-to-js languages will suffer if TypeScript syntax is adopted into the js spec (presumably causing TypeScript to gobble up more market-share).
- phil294 5y agoCoffeeScript, for one, is already at least talking about emitting TS [1]. These kinds of changes are vigorously debated though, e.g. [2]. Once ECMA type comments get to stage 4, CS would probably also adapt the new syntax. Other compile-to-js languages that already ship with their own type system like Dart will probably be indifferent to the debated proposal. [1] https://github.com/jashkenas/coffeescript/issues/5307 https://github.com/jashkenas/coffeescript/issues/5307 [2] https://github.com/jashkenas/coffeescript/issues/5394 https://github.com/jashkenas/coffeescript/issues/5394
- madeofpalk 5y ago> What about compatibility with ReasonML, PureScript, and other statically typed languages that compile to JavaScript? > While these languages compile to JavaScript, and have static typing, they are not supersets of JavaScript, and thus are not relevant to this proposal. https://github.com/giltayar/proposal-types-as-comments/#what-about-compatibility-with-reasonml-purescript-and-other-statically-typed-languages-that-compile-to-javascript https://github.com/giltayar/proposal-types-as-comments/#what...
- suydyswjuddyy 5y ago
- suydyswjuddyy 5y ago
- rd_police 5y ago
- wolfadex 5y agoEveryone keeps saying variations of "It would become possible to program (e.g.) TypeScript without compiling the source code." but that's not true. This proposal is only a subset of TypeScript, meaning that all of the existing TS infrastructure would remain and still be used. All this does is further bloat the ECAMScript for no gain.
- ARandumGuy 5y agoThis was my first thought as well, but I do think it could still be useful, even if not all TypeScript can be run as pure JavaScript. There's a lot of use cases where some type hinting would be useful, but the full feature set of TypeScript is not necessary. Long term, I could see a world where these features effectively replace TypeScript, which could help simplify dev pipelines.
- wolfadex 5y agoHow would these features replace TypeScript? TypeScript is more than just a syntax as it also requires a compiler, config, IDE tooling, and typically additional plugins to make it compatible with testing tools and bundlers.
- cphoover 5y agoI agree. The TC39 committee process has had a lot of advantages in modernizing the language, but in the last 3-5 years we've seen the pace of merging new language features grow in an unprecedented fashion. There are advantages to evolving the language but there is also a risk that the syntax becomes bloated if there is not enough deliberation within the standards process.
- eyelidlessness 5y agoI agree that there are problems with limiting this to a subset. But for the most part it’s a very good subset that mostly only removes features which would be rejected if proposed today, because they have runtime semantics. This would effectively deprecate those features in the real world. I’m in the minority who likes enums, but I can live without them. The real, big gap here is JSX. But that rightly should be a separate proposal. I just want them to consider it a prerequisite, to avoid fracturing that aspect of TS.
- shadowgovt 5y agoBut if the types don't impact the runtime, then putting them directly in the source code that would be transmitted to the client adds cost to bandwidth without benefit. Or you pass the code through a preprocessor to strip out the types and squash it before sending it to the client. At which point you have a pre-processor in your tool chain, and it might as well be a compiler from your favorite language (such as TypeScript). I think this might be reinventing the wheel to insufficient benefit.
- jakelazaroff 5y agoServices like Netlify and Cloudflare already give you the option to minify your code when serving it. Removing the types as well is a pretty small step from there.
- kevingadd 5y agoHow is it reinventing the wheel if there are already millions of LOC out there that use it? This is a debugging/development feature. The pre-processor already exists, but if you can iterate rapidly without having to run it and without having to hassle with stuff like source maps, that's a huge workflow improvement. Even without these type annotations any production javascript of moderate size is already getting minified and compressed before deployment regardless of whether type hints are used. Right now when I'm authoring typescript in vscode, I get live error feedback from tsc and eslint in the editor, so in practice I only need to run tsc to "build" because I need to strip out all the typescript syntax. If that syntax became usable in a modern browser I could skip that build step during development and only run it for deploys to CI, staging and production.
- btown 5y agoThis is essentially what Python did with its type annotations: add flexible syntax support and a standard library for e.g. Optional[dict], and let external tools like Mypy iterate on the actual type checking work. https://peps.python.org/pep-0484/ https://peps.python.org/pep-0484/ It’s a fair compromise, though now there are two invariants: all untyped JS must be a subset of typed JS, which in turn must be a subset of Typescript. And if a JS builtin like Python’s “typing” module is added to make type definitions easier and standardized, there’s now two ways to define types in Typescript. Which is far from the end of the world… but still will be somewhat controversial.
- Spivak 5y agoAnd it works pretty well except for some minor annoyances about typing things which only exist in the mind of mypy having runtime costs.
- moron4hire 5y ago>> .d.ts files often won‘t be needed either. .d.ts files contain a lot of things other than types for the emitted code. Interface types disappear completely when compiling TypeScript, but they are an important part of many .d.ts files, especially anything describing existing web APIs.
- ok123456 5y agoYou still need some way to make typed javascript run on older javascript engines. This would become yet another babel preset you have to juggle. Why not just use typescript directly in the browser?
- esperent 5y agoYou don't have to manage every feature in babel individually, just target browsers with babel-preset-env. Then there's not anything you have to do when new features get added.
- ok123456 5y agoIt's still a compilation target that needs to be managed by a build system. It doesn't address the complexity of the ecosystem, and just adds to it.
- TheAceOfHearts 5y agoDuring development it would be helpful to have type checking enabled at runtime behind some flag or configuration. I want code to fail fast and early in my development environment. In production the code will be stripped and minified. I read the FAQ in the proposal but don't understand the challenges in adding type introspection at runtime. It seems weird to add all this syntax and not have any way to leverage it during runtime. Although maybe it wouldn't be that useful? Still making up my mind about this. Glad to see that these questions are at least being considered and explored as part of the proposal. Great job from everyone involved, this proposal shows a lot of promise and it makes me excited for the future of JS.
- Kerrick 5y agoMaybe a special string flag like “use strict” — “use types”?
- jakelazaroff 5y agoI personally do not want to give developers the option to make type errors a user problem.
- themikesanto 5y agoType errors are a user problem already, if they make their way into production.
- jakelazaroff 5y agoNot necessarily — maybe the error is an incorrect argument to a function that’s never used, for example. The issue is, what should the browser do if it encounters a type error? Should it just refuse to interpret the entire script? That’s super heavy-handed when it’s possible that the error doesn’t even matter in practice.
- Aldo_MX 5y ago> It seems weird to add all this syntax and not have any way to leverage it during runtime. Just because they're not leveraging them today, it doesn't mean that they won't do it tomorrow. If a proposal requires a big effort to implement it, it will probably never become adopted.
- pavlov 5y agoA lot of what’s happened in JavaScript is just retracing Adobe’s circa 2005 proposal that nobody wanted at the time: types, JSX…
- cletus 5y agoSo this is one area where I think TypeScript made a mistake: it added syntax that wasn't compatible with Javascript. This means you couldn't seamlessly support JS and TS with the same repo. Wouldn't comments be a better solution to this given the legacy? Here's what I think the type system should allow at a minimum: 1. Scalar types (number, string) 2. Common union types (eg something that could be a number or a string) 3. This is a big one: nullability should be part of the type system; 4. Object typing that includes mandatory and optional keys and their legal types; 5. Array types (generics); 6. Dictionary types (generics); and 7. An unknown type (like "mixed" in Hack). Part of this is you need the option of preserving types at runtime and doing runtime type enforcement. This should be optional to generate a "debug" build and can be stripped out. You should be able to assert types as well as turn on automatic type checking on entry and exit to function calls as a method of finding bugs. These errors should also be available as a warning (ie print to console.log) or an error (fatal). Lastly, you should be able to easily write a type error handler to capture such violations.
- azangru 5y ago> you couldn't seamlessly support JS and TS with the same repo You could ... use a bundler, which would handle both js and ts files quite seamlessly.
- tomjen3 5y agoYou can easily work with both. Disable strict in the options (that is why it is there), then replace .js with .ts and it still works. Except now maybe you get some errors because of type inference that detects things like calling .toFixed on a string.
- chrismorgan 5y ago> Do you write minified code today? Definitely not. False. I greatly enjoy writing minified code; not only is such golfing fun, you can regularly achieve drastically smaller results. Automated JavaScript minifiers are a useful tool, but they all miss significant opportunities in even simple things like code reordering, because JavaScript’s semantics just don’t support that sort of thing. It puzzles me, given how much effort has gone into making a slow language run faster than it has any right to, how little effort has gone into making any kind of optimising compiler, for both runtime performance and bundle size. GCC and LLVM put insane amounts of effort into optimising things, which work best when paired with something like Rust’s ownership model (… so long as rustc isn’t currently being conservative after having uncovered yet another bug in LLVM’s noalias!). Meanwhile in JavaScript land, the main tool used is Terser, which is both simple and simplistic. It does very little in the way of optimisation, because it basically doesn’t seek to understand the code, and so can’t apply perform any operations that could change the semantics in such-and-such a situation that (if you tried harder) provably cannot occur. Long ago, Google made Closure Compiler, and it’s a good deal better, so long as you’re willing to humour the idiosyncrasies it requires in advanced optimisations mode, but it’s still far, far short of what GCC/LLVM can do. A few years ago, Facebook toyed with symbolic execution in Prepack, an approach with potential for building good tooling, but they gave up on it before it reached the point of being useful. Then consider other popular tools in the ecosystem: Babel is stupid (by which I mean that it doesn’t attempt to understand the code) and generates significantly bloated code because it’s seeking to match semantics as perfectly as possible without questioning whether it needs to. Bublé demonstrated a different approach, where you say “eh, who cares about exact semantics, let’s just note down the caveats and generate simpler, smaller and faster code”. (For both of these tools, I’m talking about the old ES6+ → ES5 compilations, which are obsolete now; I’m actually not sure what people use Babel for now, and how much this judgement applies.) And for bundling, webpack, which… ugh, the code it generates is just wilfully inefficient. Rollup demonstrated a different approach, where you actually care about minimising code because it makes it smaller and faster. So returning to the original point: I certainly write minified code sometimes. I have a few <script> blocks on my site (one on all pages, others on pages that use them), and those are hand-written, sometimes with an automated minifier’s help to rename variables for slightly better compression, but other than that, all manual. I’ve got a project I’ve been working on for doing DOM stuff off-thread with a tiny VM on the main thread to execute byte code, and in that I’m working the same way: I know I have to have a little main-thread JavaScript, but when automated minification can reduce my 5KB of nicely-factored code to 1934 bytes (~1185 gzipped), but manual minification can reduce it to 928 bytes (~417 gzipped) that will also run faster due to eliminating abstractions, well, I know which approach I’m going with. My way of working in these sorts of projects is that I maintain expanded and minified source codes simultaneously, and apply any changes to both. You might say “why not work in semi-minified code, applying whatever minifying transformations you have except for variable naming and whitespace, then use an automated tool for that part?” and you would have a bit of a point, except that then I’d need to worry about naming things, which can be complicated by reusing variables. Eh. I enjoy it. It’s mostly fun. A byte here, a byte there… ah, fond memories of my Casio CFX-9850GB Plus Color calculator too on which I spent hundreds of hours in my school days, often golfing my programs to save one or two bytes here or there, since I normally had at most a few kilobytes of storage space spare. I discovered at one point that they kind of had two instruction-ending characters, a line break, which was two bytes, and a 𝅍 sort of a character, which was one. Thereafter, all my source code was on one line. Those things were quite astonishing in their battery life, too; I would have racked up over 1,000 hours on it, but only went through four sets of four AA batteries. Meanwhile the newer model almost everyone else used, while about 4–10 times as fast depending on the operation, lacked colour and chewed through batteries around 40 times as fast. Then came CAS calculators, probably using 40 times as much power again… I’m rambling, aren’t I?
- overgard 5y agoI don't understand what this solves... source maps make debugging the compiled typescript easy in a web browser, and on the server you can use things like ts-node to run the typescript without compiling. Having type "comments" seems like way less utility compared to what typescript offers
- webspaceadam 5y agowhen i understood it correct it will enable you to use typescript-ish language features in standard node projects without a compilation step. which is pretty cool for small to medium size projects
- spiffytech 5y ago> I don't understand what this solves... source maps make debugging the compiled typescript easy in a web browser, and on the server you can use things like ts-node to run the typescript without compiling. As much as I love TS, integrating it into build or dev pipelines has repeatedly caused big headaches. Multi-stage source maps don't always get wired up correctly. Tools may understand TS or ESM, but not both. I would very much like this proposal to get ratified, so that my pipelines can become simpler and more robust, and so I don't need TS flavors of normal JS tools. > Having type "comments" seems like way less utility compared to what typescript offers The proposal isn't taking away anything that TypeScript offers. It lets TypeScript layer its value (types enforcement) on top of plain .js files, without getting in between the source code and tools / runtimes.
- hajile 5y agoYou still aren't going to ship all those unnecessary types in your production app, so you'll be creating a complicated pipeline anyway. The big difference here would be that your pipelines will be radically different, so you wouldn't know about random breakages in the development pipeline until you deployed to production. More importantly, this doesn't add all of TS, so you'd still have to run those tools and nothing changes except that JS is now locked in to a syntax that may or may not be the best for an actual type system in the future.
- azangru 5y agoTypescript, by the virtue of not being javascript, has evolved pretty rapidly, and has come pretty far. Would the addition of types to javascript and typescript's conformity to those type annotations slow down typescript's development? There's still some hope, at least on typescript's roadmap[0], for nominal types in addition to structural types. Will the standardisation of type annotations impose further constraints on typescript? [0] - https://github.com/microsoft/TypeScript/wiki/Roadmap#future https://github.com/microsoft/TypeScript/wiki/Roadmap#future
- Vinnl 5y agoIt's not the addition of types to JS, it's telling interpreters to ignore parts of JS source files that can then be used to insert type annotations into much like comments, e.g. for nominal types.
- ravenstine 5y agoI'd be more optimistic about official type annotations for JavaScript if said typing was less like the particularly unique syntax of TypeScript and more like that which already exists in C-family languages. For instance, in Typescript, we can do this: --- const user: User = { ... }; --- Why couldn't this be more like C rather than this weird conflation with the existing colon token? --- const User user = { ... }; --- That might seem not as pleasing to those familiar with Typescript, but it's much closer to other existing syntaxes (meaning less of a learning curve coming from Java or C). Same with function definitions: --- function foo (bar: string, baz: boolean): Qux { ... } --- Versus: --- Qux function foo (string bar, bool baz) { ... } --- I find the latter much more familiar than Typescript and less confusing. It's also slightly less verbose.
- kderbyma 5y agothen we would have another type system....no just stick with typescript or none at all...
- ravenstine 5y agoWell... yeah, I don't actually advocate for another type system, but more that if we have any type system at all for JavaScript then asking why we're going with one that overloads the colon token when it's already been sufficiently overloaded in the first place. Typescript already is what it is, and I think we should just stick with it, but if we are going to get yet another type annotation system then perhaps it might as well not be as novel as Typescript if there's a benefit.
- danielvaughn 5y agoYes exactly. There must be some good reason why TS chose the syntax they did, because a lot of it feels very old-school-java.
- stasm 5y agoType inference is one good reason. Similar syntax exists in a few modern languages, too: e.g. Rust and Swift. In languages with type inference it can be convenient that type annotations are in the postfix position relative to variable names: let user = new User(); let user: User = new User();
- masswerk 5y agoBack then, type hints for ECMAScript worked out quite well with AS3 (ActionScript3). Maybe worth revisiting? (It was also used for optimization.)
- kyberias 5y agoImagine all the time and energy wasted having all these popular programming languages re-inventing and -implementing the same features over and over again and people discussing and arguing about them.
- darepublic 5y agoOf all the new fangled crap to emerge in js ecosystem over past decade, typescript stands out to me as perhaps the best and least BS of them. I would love for typing to be supported by ecmascript but unless it arrives full featured I'm concerned it will then be typescript vs ecmascript types and landscape will simply be more cluttered with competing options. Just like how new browsers have half assed support for es6 modules. Free me from the toolchain hell of js, please, I'm waiting eagerly
- 015a 5y agoTo be frank, I hate to be the typical HN luddite, but this proposal [1] feels like it will add too much parsing complexity to runtime JS. The counter-argument to that is: everyone minifies code anyway, but this feels like a very poor argument. "Adding cruft is OK because most people have complicated build chains to get rid of it" is very different from "we've opted into a build chain (tsc) and now have access to adding cruft"; there's a default situation here, which is the many people who write JS (FE or BE) and aren't minifying it. Additionally, their pipe dream of allowing TS to become standard JS "if they stick within a certain reasonably large subset of the language" (an actual quote from the TC) is... wild. Wild. No thoughts, just vibes. Typescript is an extremely mature, fast-moving, complex project. Their list of TS features not supported under this TC is only three items long (with enums and namespaces among the list, lol), but I guarantee there are TONS of very complex type-level assertions typescript is capable of which JS is years, maybe decades, from reaching considering the glacial speed ECMA moves at. Typescript will always be a superset, which they admit. The problem is: I hold extreme doubt that JS/ECMA is even capable of communicating what that differential is to average users. Will JS support control flow analysis for dependent parameters, aliased conditions, and discriminants? Const assertions? Middle rest elements in tuples? Typescript adds all these assertions, and more, every couple months, because it turns out that type systems are something of a pandora's box. Few language-level type systems remain at the simplicity of, say, Go; most become TS, or Rust, or Java. That's not a bad thing, but not everything should be that. If this gets traction and built, JS will in-effect, though not in-requirement, turn from an interpreted language to a compiled language, whose compiler isn't even maintained by the core development teams. That's a major, major shift; and I'm not sure the proposers have even considered the ramifications of it. [1] https://github.com/giltayar/proposal-types-as-comments/ https://github.com/giltayar/proposal-types-as-comments/
- justshowpost 5y agoSeems like you entirely missed the “as comments” part. In the current proposal at least, the type annotations are just comments that can not change runtime semantics.
- 015a 5y ago
- hajile 5y agoThis adds risk with no reward. People won't use it in production because it is too big. In development, map files work fine and people will still use them because this isn't feature complete with TS. At most, it locks JS into an unchangeable type syntax that may or may not work out. Instead, we need a `use type` mode that fixes more of JS. I want type coercion gone and the super-dynamic parts of the language restricted (this both makes types more simple and makes the language more optimizable). I'd also like to see Option and Either types baked in and have `null` removed or severely restricted.
- Vinnl 5y agoThe original proposal has lots of caveats, justifications, and pre-empts many comments and questions that people seem to be asking here, so I'd recommend people to take a look at that instead: https://github.com/giltayar/proposal-types-as-comments/ https://github.com/giltayar/proposal-types-as-comments/ Also the announcement: https://devblogs.microsoft.com/typescript/a-proposal-for-type-syntax-in-javascript/ https://devblogs.microsoft.com/typescript/a-proposal-for-typ... And HN discussion: https://news.ycombinator.com/item?id=30618681 https://news.ycombinator.com/item?id=30618681
- msie 5y agoAll this hand-wringing about types in JavaScript. If Chrome just put Dart into Chrome this question would have been settled years ago. Or at least provide some mechanism where any browser can be extended with a language processor that compiles the script into webasm. The ship for extending JS has sailed! Also as I understand it webasm is still crippled in the browser with respect to accessing the DOM. Fix it somebody!
- earthboundkid 5y ago> If Chrome just put Dart into Chrome this question would have been settled years ago. Yes, but if you compare Dart to ES6, ES6 is a much nicer language, so we got lucky that they failed.
- kyle-rb 5y agoHaving used both a lot, I disagree that JS/ES6 is a nicer language. ES6 has a couple unique cool features, but also a decent amount of baggage from older JS. What major features does JS/ES6 have that Dart lacks?
- jupp0r 5y agoYou can totally compile Emscripten to wasm and do all of this as part of your application. No further browser support needed.
- superfamicom 5y agoIt seems odd to go out of the way to not break older libraries like mootools by renaming built in functions only to now break all older parsers for hints that don't convert to any performance improvement. I love the idea, and use JSDoc comments for that exact reason, but it feels inconsistent.
- tacotacotaco 5y agoYou know you can already write doc comments in Javascript code. It doesn't require changing the language. IntelliJ parses these comments when providing code insight. Yet in my entire career I have found that I am the only dev that writes these comments. I use to think this was just JS devs but I have found C#, Java, and indeed Typescript projects that I work on to be sorely lacking in comments of any kind. So, how does this adding complexity to the language standard change this?
- nyxtom 5y agoThis feels like added complexity to the runtime where the long term goal appears to make Javascript into a sort of opt-in Typescript runtime. Not sure if that's a good thing or a bad thing - but it certainly means added complexity. That being said, npm is a mix of both so it's not like you can be exclusively javascript only anyway these days (you have to be able to read and understand typescript as they are dependencies)