Catch up on stories from the past week (and beyond) at the Slashdot story archive

 



Forgot your password?
typodupeerror
×
Programming

Should JavaScript Add a New Syntax for Types? (thenewstack.io) 158

An interesting tidbit from Mike Melanson's column, "This Week in Programming."

"If a proposal unveiled this week gets its way, JavaScript developers will soon have something that many of them have long been asking for: a type system, of some sort at least." A blog post by TypeScript senior program manager Daniel Rosenwasser lays out the background and reasoning for the proposal for type syntax in JavaScript. He writes that "if we pull this all off, we have the chance to make one of the most impactful improvements to the world of JavaScript."

The proposal, which shares authors from Microsoft, Bloomberg, Igalia, and a number of other sources, suggests that JavaScript developers should be able to "add type annotations to their JavaScript code, allowing those annotations to be checked by a type checker that is external to JavaScript" and then be ignored at runtime. "Because this new syntax wouldn't change how surrounding code runs, it would effectively act as comments," writes Rosenwasser in his blog post, later adding that "JavaScript could carve out a set of syntax for types that engines would entirely ignore, but which tools like TypeScript, Flow, and others could use...."

One noteworthy part of the proposal lays out exactly what is not being proposed:

"Our team isn't proposing putting TypeScript's type-checking in every browser and JavaScript runtime — nor are we proposing any new type-checker to be put in the browser. We think doing that would cause problems for JavaScript and TypeScript users alike due to a range of issues, such as runtime performance, compatibility issues with existing TypeScript code, and the risk of halting innovation in the type-checking space." Similarly, several features from TypeScript that generate code, such as enums, namespaces, and parameter properties, are being explicitly excluded "because they have runtime semantics, generating JavaScript code rather than simply being stripped out and ignored...."

As the proposal's authors note, the proposal itself is presented as a "strawperson proposal".... Thus far, it would appear that there is debate aplenty, alongside a rather robust enthusiasm for the advent of type functionality coming to a JavaScript near you.

This discussion has been archived. No new comments can be posted.

Should JavaScript Add a New Syntax for Types?

Comments Filter:
  • by AlanObject ( 3603453 ) on Saturday March 12, 2022 @11:45AM (#62350847)

    All those arguments about Java being "too wordy" and how all that strong typing just Harshes My Mellow just went out the window didn't they?

    So if you "saw the light" now why not just use Typescript in non-strict mode?

    Personally, I use strict mode and I do just as much wordiness as I would in Java for most things.

    • by gweihir ( 88907 )

      Java? Well, a) the discussion is about JavaScript and b) Java is probably the worst designed language ever, maybe with the exception of Cobol. Java is not "wordy", it is cluttered so badly as to be nearly unreadable.

      • by narcc ( 412956 )

        Huh? What's so bad about COBOL? If you want readable yet high-performance code that will outlive you, there is no other reasonable choice.

        • by gweihir ( 88907 )

          Readable with drugs, maybe. I do not do drugs.

        • COBAL has always been shit.

          * It's overly verbose that turns signal into noise. (C's if(), structs, etc. are VISUALLY compact.)
          * No one uses UPPERCASE keywords or variables anymore except for constants.
          * Fixed column is dead.
          * Lots of other problems [c2.com] why it is retarded in 2022.

          • by narcc ( 412956 )

            If it was and has always been "shit" then why has it let us produce some of the most reliable, best performing, and long-lived applications in the history of computing?

            You're criticisms are ... silly:

            * Visually compact is not better, and can be a huge detriment to readability. I'll also point out that a lot of the "verbosity" is optional.
            * Mixed-case has been available for a very long time. Probably longer than you've been writing software
            * Can't handle properly formatting your code? Get a good IDE to

            • IDEs are crutches and a symptom of shit language design.

              Visual compact is about a good balance. C is a good compact language. Pascal and Python are shit because they were designed by idiots who didn't understand the first thing about Signal:Noise.

              • by narcc ( 412956 )

                IDEs are crutches and a symptom of shit language design.

                You've missed the point. The implication there was that the problem was with you, not the language.

                Visual compact is about a good balance. C is a good compact language.

                I do a lot in C. It is decidedly not a "good compact language". There's a reason that the IOCCC exists, after all. I suspect it's also one of the primary reasons so many languages today look like printer line noise, completely opaque to the uninitiated.

      • No, I think Perl is worse than Java. That's not to say Java isn't bad though, Java is definitely a big shit show, and has a much greater potential to make you hate life than Perl does, because nobody actually uses Perl anymore, so you're not likely to ever be stuck with it. I would say JavaScript could be worse than Java, except unlike Java, JavaScript doesn't pretend to give you a type system that isn't actually there but you still have to check against it anyways.

        • by gweihir ( 88907 )

          Well, we agree on Java.

          With Perl (which is very much in use in some fields), it really depends on the coder. I have given tons of my Perl code to students to add to or use as basis of projects and I always got the feedback that it was well readable. It requires discipline, careful commenting and no use of "clever" tricks. I am well aware that the typical coder falls short in all three aspects. These days I use Perl only for small things and as shell-script replacement. Mainly because I found that embedding

      • The only thing bad designed is continuously need for public, private etc. and idiotic coding standards that want you to make every parameter final, and the idea that "static" means a member is a class member.

        Bottom line, what counts is the library(s) and the frameworks. And serious developers use Kotlin, Scala and Groovy anyway. So Java did a good job for plastering the way for new languages.

        • by gweihir ( 88907 )

          And serious developers use Kotlin, Scala and Groovy anyway.

          Hahaha, no. That would be the hipsters of coding, the wannabees. Sure, they are not the only losers in the history of tech (or the arts) that thought they were the avantgarde.

          • You seem to be out of the loop.

            Besides Dart, Kotlin is the defacto language for Android.
            Scala is the defacto language for big data and huge enterprice systems.
            Groovy is - besides the fact of Grails and its popularity - the defacto scripting language on the JVM and with DSLs like Spock the defacto language to write tests. Unit tests and integration tests and with geb an Selenium also web driven integration tests for web applications or mobile apps.

            Calling one a hipster who is using state of the art, instead

    • Java's type system is a big pile of shit, so whatever they end up doing with Javascript, just don't make it like Java's. Granted, some of it is just a symptom of object oriented programming, but whoever thought of type erasure instead of updating the damn jvm is an asshole. You know you done fucked up when you have to re-cast Object to its correct type.

      • Java's type system is a big pile of shit, so whatever they end up doing with Javascript, just don't make it like Java's.

        Probably gonna get shot for this, but one thing in regards to typing that pissed me off about Java was their severe aversion to proper unsigned types for the longest of time.

        • me off about Java was their severe aversion to proper unsigned types for the longest of time.
          That is extremely annoying indeed.

      • Seems you know nothing about Java.
        There is nothing wrong with Java's type system. It is an ordinary type system like any other strong typed language, e.g. Pascal or C++.
        Perhaps you are confusing Java with Javascript?

        but whoever thought of type erasure instead of updating the damn jvm is an asshole
        Type erasures only exist in expanding of Generics.

        You know you done fucked up when you have to re-cast Object to its correct type.
        Exactly. But that means YOU (ArmoredDragon) has fucked up. Learn to avoid "down cast

        • Seems you know nothing about Java.
          There is nothing wrong with Java's type system. It is an ordinary type system like any other strong typed language, e.g. Pascal or C++.

          lol you're serious...Well Mr "I have a CS degree which means I know better than you", let's just say that not all type systems are the same, and the difference between them in any two languages can be either very big or very subtle.

          Perhaps you are confusing Java with Javascript?

          You do realize I contrasted the two in that very post you responded to, right?

          Type erasures only exist in expanding of Generics.

          Umm...ok...

          Has it occurred to you that C# is based on practically the same design principles as Java and yet it doesn't have to do that? Or that C++ has RTTI where Java relies on reflection?

          Oh but all t

    • Comment removed based on user account deletion
      • by swilver ( 617741 )

        Hi ancient one, Java has been updated as recently as 2014, before anyone even knew Go or Rust existed. Reading all lines of a file into strings is a one liner. See Files class.

  • by jd ( 1658 ) <imipak@yahoGINSBERGo.com minus poet> on Saturday March 12, 2022 @11:49AM (#62350861) Homepage Journal

    I can see the argument for adding constraints that can be validated. Spark, the secure version of Ada, does this.

    However, it seems stupid to limit it to types. Just make it a full fledged constraint system that can have any type of constraint, where types are the first sort to be defined, allowing coders to write others.

    But if you're going to do that, you might as well define a cleaner syntax for the primary language. JavaScript is ugly and would limit the usefulness of verification systems.

    • by gweihir ( 88907 )

      Well, you could go straight to using, say, Python instead.

      • by narcc ( 412956 )

        We want to improve things, not make them worse.

        • by gweihir ( 88907 )

          We want to improve things, not make them worse.

          Indeed. And we most decidedly want to get rid of anybody that thinks Python is a bad language. That would remove all the semi-skilled right at the start.

          • by narcc ( 412956 )

            Wow, okay. I know exactly how much weight to give your opinions on programming language design... Wow.

            • by gweihir ( 88907 )

              Wow, okay. I know exactly how much weight to give your opinions on programming language design... Wow.

              Well. Maybe when you have done real work with, say, 20 different programming languages you will understand.

              • by narcc ( 412956 )

                LOL, okay. Whatever you say. Enjoy rewriting everything every few years.

                • by alcmena ( 312085 )
                  You mean like writing in Swift? (Not defending Python, I think it's awful too. Just the whole "throw away all your code and try again" isn't unique to it)
                  • by narcc ( 412956 )

                    I agree. It's a real problem that surprisingly few people seem to be worried about. So short sighted...

          • Indeed. And we most decidedly want to get rid of anybody that thinks Python is a bad language. That would remove all the semi-skilled right at the start.

            Admittedly my view is skewed since I work in an engineering department at a university, but - most of the people I know who rely on python are not very skilled at all. They learned python because 1) their colleagues know python, and 2) python lets them quickly get to a "I can hack something together" level of ability (I swear they mostly learned the language by reading stack overflow pages). But they repeatedly demonstrate a lot of glaring holes in their knowledge of computing or coding in general.

            • by gweihir ( 88907 )

              Sure. Python coders are a different question. Like most coders, most Python coders are incompetent. Since some people think Python is suitable as a first programming language (something I very much do not think) the average Python coder may be even less competent that the average, say, Java coder and the average Java coder is pretty bad. But that does not reflect on the language. Python is both suitable for "quick hacks" and large projects. Most _coders_ on the other hand cannot do large projects competentl

              • by alcmena ( 312085 )
                Java devs certainly have devolved through the years. It's rare I can meet one who knows how to code a service without adding in Spring Boot and a crap ton of frameworks. Those are ok in the VM / Container world but when in autoscaling envs (Google App Engine, AWS Lambda, etc), the overhead is horrible. Yet, they can't seem to break away from the pattern.
                • by gweihir ( 88907 )

                  That is probably all they know. Writing a service from scratch is something that requires real understanding of how things work.

          • Python might not be a bad language if it didn't depend on whitespace. But I personally have had actual problems just copying and pasting examples from websites because of it. If a common conversion error can destroy your code, then your code doesn't have enough structure in it. Take every single newline and excess (non-quoted) bit of whitespace out of a C program and not only does it still work correctly, but you can recreate the structure with a simple program.

            Literally the only real argument against Pytho

    • by Tablizer ( 95088 )

      I was thinking a LINQ-like ability would allow parse-based validation function "attachments":

      function foo( i.int(), d.date(), n.num() ).int
      {
      ...
      return i + 7; // func return type is int
      }

      And maybe be able to use these operations ANYWHERE in the function body to check the type:

      var myNum = x.int() + y.num();

      We could also do:

      var myNum.num() = x + y;

      or

      var myNum.num() = x.int() + y.num();

      Don't really need it for strings, as everything can "be" a string using parse-base validation. And it doesn'

      • by jd ( 1658 )

        Agreed. And a syntax like that can be trivially extended, so you could have:

        return i + 7; // func return type is int; i > 3

        There could be some sort of filter so that only constraints that could be parsed would be handled, but that would be relatively easy.

    • Do you want to get Racket? Because that's how you get Racket.
    • Just make it a full fledged constraint system that can have any type of constraint, where types are the first sort to be defined, allowing coders to write others.Could I write a constraint preventing the programmer from using Javascript in the first place?

  • by Tablizer ( 95088 ) on Saturday March 12, 2022 @11:52AM (#62350867) Journal

    I've become addicted to C#'s optional named parameters and wonder way JavaScript et. al. don't have them. They are absolutely wonderful. Object literals can kind of emulate them, but are too awkward and verbose for common use.

    That's my number one request. Also, bolting on types after the fact will probably create a lot of awkwardness such that I'm skeptical it will solve more problems than it creates.

    • Everyone's needs are different. It depends on many factors, including the nature of the problem you are solving. In some problem spaces, lightning fast speed is far more critical than ease of code maintainability. But in many problem spaces, the exact opposite is true.

      Object-oriented purists like to insist that object oriented design (with plenty of dependency injection and inversion of control) is the One Correct Way to code anything and everything. But kernel developers will just laugh. The performan

      • by ceoyoyo ( 59147 )

        Javascript's biggest problem was alleviated by finally introducing an import statement. Well, sort of. Javascript's second biggest problem is that you need a mile long toolchain, with a half dozen options for each step, to actually do anything, including use the import statement....

        It is getting better, but type hinting seems to me to be pretty far down the list. It's trendy right now though.

      • But kernel developers will just laugh. The performance costs of virtual methods is prohibitive when you are operating at that level.
        That is just silly.
        A) you most likely would not use a virtual function often
        B) as soon as you pass parameters, the look up overhead is close to zero.

        ATM there is only one real kernel under development, that is Linux. And it does not use C++ because Linus hates it, that is all. And I'm not a kernel developer as plain old C is a pain in the ass ...

    • To me that makes function signatures way too long in many cases.

      Over the last few months of going back and forth between Java, C#, and Rust for different projects, I think I've learned to dislike overloading in general. Especially after I modified one of the overload signatures in a big Java project I'm working on that lead to a rarely occurring stack overflow bug that was caused by very subtle misplacement of a null parameter from one of the signatures that took fewer arguments, and took me a long time to

      • And how ironic it is that Java is now the closed language where C# is now the open one?
        That is nonsense. They are similar open.

        The whole C# language is MIT licensed no less, which means hell hath frozen over in Microsoft land. If you use the latest versions of Java, Oracle might sue you even after you've paid them already,
        Java is Apache licensed.
        Oracle is only rebundling the Apache's OpenJDK. And: Apaches OpenJDK is even hosted by Oracle ...

        What your languages problems are, I don't know. Perhaps when you a

        • That is nonsense. They are similar open.

          No, they're not. Oracle's JDK has closed source bits that aren't in the OpenJDK. In order for anybody to produce a JRE or JDK and actually call it Java, it also has to go through the decidedly non-open JCK.

          Compare that to C#. Want to contribute? Submit a pull request. Like this one:

          https://github.com/dotnet/csha... [github.com]

          Oh and look at that, C# is getting real tuples. Imagine that. I'd be surprised if Java ever gets a real anything. Technically Java still doesn't even have real generics.

          Java is Apache licensed.

          It's hard to say Java is an

  • Personally I love TypeScript. I wouldn't work on any non-trivial project that didn't use TypeScript in lieu of JavaScript. I've personally seen bugs more times than I can count that would not have happened in the first place if the code had been using TypeScript.

    At the same time if it doesn't involve me, then I'm live and let live and seems like those that prefer JavaScript over TypeScript don't really want this and those that like what strong typing gives them have TypeScript, so why do we need some half

  • Exactly what is needed, more complexity, not like there isn't enough issues with Javascript.
    • by narcc ( 412956 )

      Yeah, ES6 broke the language. Now, it's like two fundamentally different languages awkwardly mashed together. For goodness sake, how you declare a function changes the behavior of `this`! It's pure madness.

      They've taken a simple, powerful, and expressive language and cluttered the hell out of it with useless crap designed to make it work more like Java. All because the average developer couldn't take a couple days to actually learn the language. The standards committee has lost their collective minds.

  • Put a bullet in its head and leave that hateful, spiteful language dead on the side of the road.
  • With the advent of Typescript, Iâ(TM)d say that JS should either delegate type support to Typescript, or treat Typescript as the successor to typeless JavaScript. It already is in many NodeJS based projects.

    • by narcc ( 412956 )

      I agree. If you don't understand JavaScript or how to effectively use dynamic languages, then TypeScript is the way to go. They really need to leave the language alone, and stop trying to turn it into something fundamentally different.

  • by gweihir ( 88907 )

    This atrocity cannot be saved. Just do away with it and go to something sane.

  • by WierdUncle ( 6807634 ) on Saturday March 12, 2022 @12:27PM (#62350941)

    A fundamental problem in computing is writing stuff, which is just a sequence of numeric codes, and getting a desirable result when those codes are interpreted by an algorithm. When I started out doing scripty stuff, using Perl, the clever compiler would theoretically Do The Right Thing. Except, in practice, it often didn't, and then I had the problem of figuring out what the clever compiler thought I meant, rather than what I intended.

    When you specify types, rather than let the fancy compiler make guesses, you have more control over what is going on. The fact that this needs more words to say what you want is a benefit, not a hindrance. I have seen plenty of coders who can type faster than they can think. There really is far too much code out there that happens to work, but nobody knows why.

    • by narcc ( 412956 )

      When you specify types, rather than let the fancy compiler make guesses

      I see you don't understand dynamic languages. That might be the larger problem here.

      • I do understand dynamic languages. I use Python for various jobs at work. It is nice to have a simple way to express simple tasks. I like Python partly because it is quite strict about types. For example, if I have a string, that may represent a number, I have to tell the compiler that I want to make that interpretation, using a conversion function. The extra typing is minimal overhead, compared to figuring what type the smarty-pants compiler has decided what type my variable has, on this particular occasio

  • Typescript is another monolithic contribution to the browser by Microsoft - the same people who brought Silverlight, whatever UWP was. It's a massive investment and double-down on Javascript's current type system.

    Typescript's massive type database is a massive technical debt that will prevent Javascript from ever evolving past it's ad-hoc type system.

    Any relevant new version of Javascript should keep Javascript's "the best parts" and add a type checking system. The benefit to Typescript is not in th
  • Stick a fork in JS already, it's an abomination with so many bandaids on top it's silly.

    Once upon a time, the SRC the <script> tag if I recall had a TYPE= attribute -- just *use* it to specify one of many languages so people can use what they want.

    Make a standard plugin interface to compile the desired language to WebAssembly, freeze the DOM/HTML/plugin/CSS/blah blah standards and stop the insanity.

    Better yet, as others have said, ditch this entirely and go back to CGI and minimal web browsers. Oh but

  • The main problem I've found when operating without types is that it can become pretty unclear what exactly is in a given object. What's the field name? What type is it? Is it an array/list/object?

    That adds a bit of time because you have to dump the object to figure out what the heck's in it.

    It also makes code fragile, because anyone upstream or downstream can add/change/delete anything.

    In large project that will definitely cause problems, especially on a rapidly-changing codebase. It probably leads to a lot

    • But you do know what a version control system is, or source code control system?

      How someone can modify something upstream or downstream without you noticing is beyond me ...

  • I mean something that acts like a compile time step, it runs once and checks things including browser functionality for parts of imported libraries used. It could also check types. Ultimate goal would be a set of restraints placed on Javascript that allow it to be compiled to webassembly.

  • How very oxymoronic. Let's take a scripting language and try to make it a programming language by throwing more garbage on top. Kludge upon kludge; always good for runtime performance.

    • Let's take a scripting language and try to make it a programming language

      It's already being widely used in cases far beyond what any scripting language should be used for. Whether we agree with it or not, there's clearly a demand for a proper programming language in the browser. The only reason I can see which has prevented someone from creating that is the fact that JS is the only language that has widely-supported access to the DOM. Maybe WebAssembly will fix that, but given its slow adoption rate by

  • Sheesh! It's a metaphor, not a label attached to an actual person (e.g., Chairman).
  • https://medium.com/javascript-... [medium.com]

    In short, no number of Hail Mary's s going to save this cursed language. It's been fragmented, without governance, guidance and proper standards for too long.

  • by PPH ( 736903 )

    ... if the type checker throws a bunch of errors, I just fix the annotations to make them go away. Regardless of whether the annotations actually reflect the actual code or not.

    Yeah. That's going to work well.

  • The strengths of JavaScript are found in that it was everything Java was intentionally not. In large part, it's that it was not a strongly typed language. JavaScript was meant to be a simpler companion, sort of beginners' language, to Java. The lack of all those allegedly "advanced" concepts and features in Java is what made JavaScript a vastly more productive and faster-executing language.

    In nearly all cases, it is more efficient and easier for the compiler to determine what the types should be. It eli

    • by hjf ( 703092 )

      Yes, yes, javascript just works because it will accept anything you throw at it and fail silently.

      Good luck chasing down that bug on production because you missed a parameter in your function call. And JS, as productive as it is, is just passing "undefined".

      I don't know what the hell is wrong with you "fast coders". I wonder if you ever worked on a project with more than one developer, or if you ever wrote a fucking unit test (because tests, ugh, those ARE a waste of time, right?)

    • You keep mixing up:
      weak type system (or no types) < - > strong type system
      static type system < - > dynamic type system

      Except for a few design flaws (actually bugs, no idea why they never got fixed) of automatic converting strings into numbers and booleans and similar flaws:

      JavaScript is a strong typed but dynamic typed language.

      In other words: it has types. Plenty of them. You just do not declare variables with a a type, because it is dynamic typed.

    • Don't "fix" duct tape so it's better at anything; it's good enough at everything and that is it's power - make it best for something and you ruin its wide utility.

      Javascript (like most scripting) should be a duct tape for combining components together. JS is exceptional at this with it's ability to modify external objects and define setters and getters. The use of macros was a big mistake in not including them as it could hold off many of changes after ECMA 5 which are largely not needed but using macros a

  • You can check types if you want in Common Lisp. It gives two advantages: it lets the compiler create faster code when needed, and it lets the coder design more strict code if he needs to.

    But you do not need to use it, you can start coding, make sure your basic algorithms work, and then improve them incrementally where needed.

    Proving that a type system does not need to be a fixed part of the language.

    And that is the problem with all "modern" languages, derived from C or Algol, most of the time they force

"Ninety percent of baseball is half mental." -- Yogi Berra

Working...