News for hackers. Stuff that matters.
Re:TypeScript Is Surprisingly OK for Compilers by lmm on Friday August 18, 2023 @02:42AM (#37172079)
Is that really suprising? Typescript is yet another language that has, kicking and screaming, picked up most of the ML featureset. I'd expect it to be, well, fine; the lack of real pattern matching is a pain, so it's going to be inferior to OCaml, but fine, no different from using C# or Swift or Dart or Kotlin or something of that ilk.
Re:TypeScript Is Surprisingly OK for Compilers by moonchrome on Friday August 18, 2023 @03:28AM (#37172349)
That's some very high level view - in reality even tough those languages are in similar categories the experience would be vastly different :

TypeScript - powerful type system but shit underlying stdlib and language (no pattern matching/switch expressions)

Dart - worse than TS because the object model is closed - so no dynamic freedom, but the type system and expressions are weaker then the rest. Also 0 meta programming facilities - Java level of boilerplate and code generators

C# - closest to ML featureset out of the mentioned, but unlike TS doesn't have sum types which will make a lot of things more tedious.

Re:TypeScript Is Surprisingly OK for Compilers by pja on Friday August 18, 2023 @04:07AM (#37172631)
If you’re going to use C# for a compiler, why not go the whole hog & use F#?
Re:TypeScript Is Surprisingly OK for Compilers by moonchrome on Friday August 18, 2023 @07:43AM (#37174347)
No argument from me, just saying lumping in all those languages together sounds reasonable in theory, in practice they are very far apart.

You'll probably have similar overlap between C# and F# implementations as you would with say TypeScript - they are just that different in practice IMO.

Re:TypeScript Is Surprisingly OK for Compilers by delta_p_delta_x on Friday August 18, 2023 @11:24AM (#37176899)
I was going to mention F#. The parent and grandparent comments mention C# and ML, and the intersection of the two is... F#.
Re:TypeScript Is Surprisingly OK for Compilers by crooked-v on Friday August 18, 2023 @04:35AM (#37172826)
> no pattern matching/switch expressions

They're still waiting on the do expression proposal for that (https://github.com/tc39/proposal-do-expressions), which has been in the bikeshedding stage for the past five years.

Re:TypeScript Is Surprisingly OK for Compilers by yunohn on Friday August 18, 2023 @05:47AM (#37173354)
I’m not clear on the benefits of this proposal over just using anonymous functions. Some of the examples just seem contrived.

And the React example makes no sense, you can use a ternary and it is even shorter.

``` return ( <nav> <Home /> {loggedIn ? <LogoutButton /> : <LoginButton /> } </nav> ) ```

Re:TypeScript Is Surprisingly OK for Compilers by doctormanhatten on Friday August 18, 2023 @06:13AM (#37173595)
Having written quite a lot of Reason react (similar in syntax to the proposed React example) - while in this particular case because the example is so simple the ternary looks nicer, its also nice to just have a longer expression block in the middle of your JSX when you're doing more complex things.
Re:TypeScript Is Surprisingly OK for Compilers by baq on Friday August 18, 2023 @06:09AM (#37173566)
for me the point is to be able to return from inside multiple expressions from the correct scope i.e. the root function without throwing.
Re:TypeScript Is Surprisingly OK for Compilers by graftak on Friday August 18, 2023 @07:03AM (#37173992)
What if you want a `switch` instead?
Re:TypeScript Is Surprisingly OK for Compilers by graftak on Friday August 18, 2023 @07:02AM (#37173977)
The proposal for pattern matching syntax seems more akin to what they're looking for.

https://github.com/tc39/proposal-pattern-matching

Re:TypeScript Is Surprisingly OK for Compilers by jezzamon on Friday August 18, 2023 @09:59AM (#37175705)
Could you speak more to the dart, and specifically the "Java level of boilerplate and code generators"?

I've used it a bit but I haven't found it very boilerplatey in general, so I'm interested in learning what contexts you run into that.

I'm assuming you're using it with flutter?

Re:TypeScript Is Surprisingly OK for Compilers by munificent on Friday August 18, 2023 @01:08PM (#37178717)
Your understanding of Dart sounds a little outdated. We have a fully sound static type system and the language is pretty expressive, especially with the new pattern matching stuff in 3.0:

https://medium.com/dartlang/dart-3-1-a-retrospective-on-func...

Re:TypeScript Is Surprisingly OK for Compilers by dejawu on Friday August 18, 2023 @03:36AM (#37172412)
I'm quite fond of this library for pattern matching; it's a staple in all my new projects.

https://github.com/gvergnaud/ts-pattern

Re:TypeScript Is Surprisingly OK for Compilers by baq on Friday August 18, 2023 @03:32AM (#37172383)
The biggest expressivity pain point in practice for me is try/catch not being an expression, so I can’t do

   const c = try { … }
Re:TypeScript Is Surprisingly OK for Compilers by lovasoa on Friday August 18, 2023 @03:46AM (#37172478)
With async code, there is

    const c = myAsyncFun()
               .catch(e => …)
Re:TypeScript Is Surprisingly OK for Compilers by WorldMaker on Friday August 18, 2023 @10:28AM (#37176117)
That leaves c as Promise which was not the type they were looking for. You'd still have to unwrap the promise and deal with the result or rejection. The easiest way to do that is to use await, and if you are using await you'd be better off using try {} catch {} around the async function than .catch().
Re:TypeScript Is Surprisingly OK for Compilers by jve on Friday August 18, 2023 @03:56AM (#37172554)
Yes! This just drives me crazy:

   string something = null;
   try {
      something = mayThrow();
   } catch (SomeException ex) {
      log.Info(ex);
   } catch (Exception ex) {
      log.Fatal(ex);
      throw;
   }
   if (something != null) {
      ...
   }
Would be actually nice if it had F#'s try...with https://learn.microsoft.com/en-us/dotnet/fsharp/language-ref... and would allow us something like:

   var something = try {
     mayThrow()
   } with (SomeException ex) {
      log.Info(ex);
   } with (Exception ex) {
      log.Fatal(ex);
      throw;
   }
Or some way to do pattern matching on exceptions for switch expression.

   var something = mayThrow() switch {
     (SomeException ex) => {
       log.Info(ex);
       return null;
     }
     (Exception ex) => {
       log.Fatal(ex);
       throw;
     }
     var passThru => passThru
   }
Re:TypeScript Is Surprisingly OK for Compilers by scotty79 on Friday August 18, 2023 @05:55AM (#37173436)

   var something = (() => {
     try {
       return mayThrow()
     } catch(SomeException ex) {
       log.Info(ex);
       return null;
     } catch(Exception ex) {
       log.Fatal(ex);
       throw;
     }
   })();
Close enough?
Re:TypeScript Is Surprisingly OK for Compilers by baq on Friday August 18, 2023 @06:05AM (#37173530)
not really; can't immediately return from the lambda caller without throwing, always have to either try/catch anyway or if/else the return value of the lambda. (also, it's rather ugly to read and inconvenient to write.)
Re:TypeScript Is Surprisingly OK for Compilers by jve on Friday August 18, 2023 @07:02AM (#37173986)
Another idea, introduce ??? that would invoke on exception :)

   var something = (mayThrow()
      ??? (SomeException ex) => { log.Info(ex); return null} )
      ??? (Exception ex) => { log.Fatal(ex); throw; };
Or maybe just start using Results as return type and get ValueOrDefault :) But when it comes to handling exceptions, I think it explodes there with ifs and processing IENumerables: https://github.com/altmann/FluentResults

But then again, simpler Results wrapper may be used perhaps. But it is a different way of coding and takes some mental shift on how to think about errors and distinguish between error results and true exceptions.

Oh, csharplang already had discussion on the matters about try/catch single statements: https://github.com/dotnet/csharplang/issues/786

Re:TypeScript Is Surprisingly OK for Compilers by scotty79 on Friday August 18, 2023 @06:47PM (#37183117)
> can't immediately return from the lambda caller without throwing

You want to immediately return in the middle of something that was supposed to simulate just evaluating an expression?

You can't immediately return in the middle of 2+2 as well because return is a statement and can't be a part of expression.

Re:TypeScript Is Surprisingly OK for Compilers by thdespou on Friday August 18, 2023 @04:01AM (#37172593)
Zig can though:

  const std = @import("std");

  pub fn main() !void {
    const stdout = std.io.getStdOut().writer();
    try stdout.print("Hello, {s}!\n", .{"world"});
  }
Re:TypeScript Is Surprisingly OK for Compilers by zkldi on Friday August 18, 2023 @04:15AM (#37172688)
that's not using `try` as an expression. can you do `let foo = try <code> (plus some handling for diverging in the other case?)`
Re:TypeScript Is Surprisingly OK for Compilers by kaba0 on Friday August 18, 2023 @04:36AM (#37172830)
It can and you in fact either have to mark that you return that error when you use try, or you have to provide a default value in a catch block:

``` fn potentiallyErrorReturningFunc() !u64 { ... }

const foo = potentiallyErrorReturningFunc() catch { 0 }; ```

One notable difference to most other languages is it being a value only, basically a product type of return value XOR error. These error values get serialized into a number by the compiler that is unique, and on the type system level you deal with sets of these error values. Quite clever in case of a low-level system, in my opinion.

Re:TypeScript Is Surprisingly OK for Compilers by flohofwoe on Friday August 18, 2023 @06:14AM (#37173602)
> const foo = potentiallyErrorReturningFunc() catch { 0 };

Nitpick, but AFAIK this won't work and needs to be rewritten either to:

    const foo = potentiallyErrorReturningFunc() catch 0;
...or to:

    const foo = potentiallyErrorReturningFunc() catch blk: { break :blk 0; }
(I wish there would be a more convenient way to return a value from a scope block, not necessarily with a "dangling expression" like Rust, but maybe at least getting rid of the label somehow)
Re:TypeScript Is Surprisingly OK for Compilers by flohofwoe on Friday August 18, 2023 @06:03AM (#37173512)
Yes, 'try' can be used like an expression in Zig which resolves to the unwrapped success-result of an error-union, or in case of an error immediately passes the error-result up to the calling function.
Re:TypeScript Is Surprisingly OK for Compilers by xscott on Friday August 18, 2023 @04:12AM (#37172664)
What does a try expression like this do? Returns null/undefined on a throw?

I suspect you could do something like:

    const c = attempt(() => ... );
where attempt invokes the lambda, catches any exceptions, and does what you want
Re:TypeScript Is Surprisingly OK for Compilers by lmm on Friday August 18, 2023 @04:33AM (#37172811)
> What does a try expression like this do? Returns null/undefined on a throw?

If an exception is caught, the expression evaluates to what the catch block evaluates to. (Similar to having if/else be an expression). Of course if the exception isn't caught then it propagates so the expression doesn't take a value.

Re:TypeScript Is Surprisingly OK for Compilers by afandian on Friday August 18, 2023 @10:15AM (#37175915)
Kotlin has this feature (`try` and `if` are expressions not statements), and a good model for return values. https://kotlinlang.org/docs/exceptions.html#exception-classe...
Re:TypeScript Is Surprisingly OK for Compilers by not_alexb on Friday August 18, 2023 @04:22AM (#37172738)
I use iife for stuff like this.

const c = (

    ()=> {
        try: {...}
    } 
)()
Re:TypeScript Is Surprisingly OK for Compilers by smcl on Friday August 18, 2023 @05:01AM (#37173015)
Would you not just move that `try { ... }` block into a separate function or method?
Re:TypeScript Is Surprisingly OK for Compilers by austin-cheney on Friday August 18, 2023 @05:43AM (#37173320)
I never ever use try/catch in my code. The only time its really necessary is to wrap JSON.parse on use of untrusted input. For everything else it just feels sloppy as through there is insufficient logic in place for handling primary conditions versus edge cases. Also, try/catch will never compile in the JIT.
Re:TypeScript Is Surprisingly OK for Compilers by macguillicuddy on Friday August 18, 2023 @06:46AM (#37173836)
Perhaps the place I use it most is that try/catch is how you deal with rejected promises that you've `await`ed in an `async` function.
Re:TypeScript Is Surprisingly OK for Compilers by raxxorraxor on Friday August 18, 2023 @09:20AM (#37175223)
For everything with the slightest bit of I/O it is quite practical if you have even the most trivial assumptions about its form.

Sure, you can check for everything. It often is more effective, but not prettier or easier to read and of course you also will miss cases.

Re:TypeScript Is Surprisingly OK for Compilers by austin-cheney on Friday August 18, 2023 @12:10PM (#37177720)
This sounds like some hyperbolic framework nonsense. First of all I/O just means access to an API. I am going to presume you mean messages from a network.

In that case a message from a network either sends or fails and in the case of sending try/catch does nothing for you but provide an error object, and you don't need try/catch to capture the error. In the case of receiving a network message the message comes in or it doesn't. If the message does come in and is malformed your application should be mature enough to handle that appropriately to the benefit of the user instead of crapping out some error messaging to the console. You don't need try/catch to do any of this. A simple if condition is more than sufficient.

> check for everything

You should check for everything. You only need to check for one thing and if you check for it you are already at 100% of everything. Did you get what you expected: Yes/No?

Re:TypeScript Is Surprisingly OK for Compilers by thrashh on Friday August 18, 2023 @12:45PM (#37178321)
Disagree.

Usually you don't need to just know if there is an error or not -- sometimes you need to know what that error is. For example, an I/O error versus your image-is-too-small error -- you need to respond to the user differently. I've seen plenty of web apps that treat I/O errors and user input errors as a generic "an error happened" and that is completely wrong. Proper exception bubbling means none of that code that encounters the errors needs to necessarily know how to handle the error and your app always responds correctly.

That said, I don't use exceptions as much in JS because exception handling in JS is still very nascent. There's no base library of exceptions and telling different exceptions apart is not built-in to the language. In a language with more mature exception handling, it's a breeze.

Re:TypeScript Is Surprisingly OK for Compilers by austin-cheney on Friday August 18, 2023 @01:00PM (#37178574)
You made the same mistake as the grandparent by assuming I/O means something more specific than it does. At any rate there isn't a good reason to bubble error objects out of the event handler and secondly even if you did you would have everything you need to fully describe the problem within the error object including the stack trace, event type, error message, and so forth.

Its an equivalent breeze in JavaScript as well unless you are fumbling through abstraction layers (frameworks) that eliminate the information you need.

Re:TypeScript Is Surprisingly OK for Compilers by thrashh on Friday August 18, 2023 @04:30PM (#37181675)
Not at all. You don't have to describe anything when throwing an error because that's the point of exception inheritance. Second, the whole point of exceptions is to bubble them out of the handler(!) because otherwise you would use return values (like in Go).

Since you are saying that you have to describe the problem within the error object, it sounds like you must be you are parsing error messages and stack traces to figure out what the error is. That's not how exceptions are to be used and I think that's why you are not seeing why you would bubble errors.

In other languages, you don't have to do any of that nonsense because object identity is much stronger, but JavaScript uses prototypical inheritance so you can't really tell if an error is an ImageError or an IOError. Despite this issue, exceptions were added to the JavaScript language without resolving that problem. The reason why you have to worry about frameworks eliminating error information is because that problem wasn't resolved and so frameworks roll their own error handling and there is no standard.

Re:TypeScript Is Surprisingly OK for Compilers by afavour on Friday August 18, 2023 @09:29AM (#37175329)
> Also, try/catch will never compile in the JIT

Changing the way you program to fit what a JS compiler does or doesn't do is a fool's errand, IMO. The performance benefits are likely to be minimal, confusion for anyone else who has to touch the codebase is high.

Re:TypeScript Is Surprisingly OK for Compilers by madeofpalk on Friday August 18, 2023 @11:43AM (#37177212)
And, JS engine's whims change frequently enough that yesterdays micro-optimisation is today's deopt.

Much better to just write ideomatic code.

Re:TypeScript Is Surprisingly OK for Compilers by austin-cheney on Friday August 18, 2023 @12:00PM (#37177557)
That depends on how many changes it requires. If its just a matter of don't do these 3 things and your code suddenly becomes more predictable its like being slapped with a magic wand. Everybody wins. All you have to do to ensure 100% of your code compiles in a JIT is be predictable. Predictable code is, on its face, always less confusing.

> The performance benefits are likely to be minimal

This makes me cry, but not a cry of joy or ecstasy. People guessing about performance is perhaps the most frequent anti-pattern in all programming. Please read the following document, you can skip to the end but it may not make much sense if you do.

https://github.com/prettydiff/wisdom/blob/master/JavaScript_...

When developers make random performance assumptions, defensive assumptions are worse, it immediately identifies a lack of professional maturity. Its like small children playing games that expand their imagination, which is great for small children but less great for developers pretending to be adults.

Re:TypeScript Is Surprisingly OK for Compilers by afavour on Friday August 18, 2023 @12:26PM (#37178004)
> People guessing about performance is perhaps the most frequent anti-pattern in all programming

I disagree, premature optimisation is.

Changing your style of programming to suit what todays JIT does but tomorrow’s may not, in anticipation of performance issues you have not yet encountered is a waste of everyone’s time. No doubt it is valuable in extremely performance sensitive code but that is the extreme minority, especially in the JavaScript world.

If thinking this makes me a “small child” in your mind I’m fine with that.

Re:TypeScript Is Surprisingly OK for Compilers by austin-cheney on Friday August 18, 2023 @12:49PM (#37178400)
What you are advocating, the guessing about performance, is the premature optimization. Don't feel bad, most developers have no idea what that term really means. Here is the original essay where it comes from: http://web.archive.org/web/20130731202547/http://pplab.snu.a...

Premature optimization is the extra effort required to alter work necessary to circumvent guessed optimization pitfalls. In the same breath Knuth advocates always targeting known performance advantages.

Re:TypeScript Is Surprisingly OK for Compilers by afavour on Friday August 18, 2023 @12:54PM (#37178483)
> Don't feel bad, most developers have no idea

Some advice I know you’ll ignore: your tone in the comments here is deeply patronising. You know absolutely nothing about me and yet are entirely comfortable dismissing my perspective as wrong simply because yours must be correct. It’s not an interesting or rewarding way to converse, it makes me want to stop talking to you as soon as I can. Which I’ll be doing here. Have a good weekend.

Re:TypeScript Is Surprisingly OK for Compilers by austin-cheney on Friday August 18, 2023 @01:58PM (#37179578)
Yes, I work in a language where junior developers and people deeply unaware of the language advocate anti-patterns and bad practice as matters of law, often for personal defensive reasons. Its hard to not feel patronized. You are correct in that I do not know you, but I have been doing this work long enough to see when people hide behind abstractions they don't understand as necessary to mask their level of confidence and then argue from for best practices from that perspective.

My best possible free advise: only advocate to what you practice. If, for example, you have never written an application in JavaScript without a framework, such as Angular, then you are an Angular developer not a JavaScript developer. If you speak to something you have never practiced with a presence of authority people with 10, 15, or 20 years experience will be condescending. That is why imposter syndrome is a thing. Its better to get the unexpected honesty from some irrelevant guy online than get hired into a job and either get it in person or worse compensating for a manager with imposter syndrome.

Re:TypeScript Is Surprisingly OK for Compilers by afavour on Friday August 18, 2023 @03:23PM (#37180779)
This is exactly what I’m talking about. You are assuming I am inexperienced and have no idea what I’m talking about because I have a different view to you.

For what it’s worth, I’ve spent years working with the innards of various JS engines, managed deployments of JavaScriptCore inside iOS apps (fun fact: no JIT) and using QuickJS in low resource environments (no JIT there either). There’s an interesting conversation to be had around optimising your code for the JIT, given the different environments we’ve both worked in. But your ego won’t allow it to take place. A shame for all concerned but in my years of development I’ve met plenty like you and I’m well aware that I’m not about to change your mind so I’ll just leave it there.

Re:TypeScript Is Surprisingly OK for Compilers by eyelidlessness on Friday August 18, 2023 @12:12PM (#37177749)
> Also, try/catch will never compile in the JIT.

If this is an actual concern (as in you have measured and try/catch is actually affecting something performance sensitive): you can most likely mitigate the impact by isolating the try/catch bodies in separate functions.

I haven’t verified this in every JIT, but I saw meaningful perf improvement in V8 for real world degenerate cases where the performance did actually matter and make a significant difference. But seriously, as always, measure before optimizing stuff like this! It might matter, but it seldom will for anything more than academic curiosity.

Re:TypeScript Is Surprisingly OK for Compilers by magicalist on Friday August 18, 2023 @01:26PM (#37179070)
> Also, try/catch will never compile in the JIT

This was only ever true in V8, and hasn't been the case since 2017 with the optimizing compiler switch from Crankshaft to TurboFan.

Take a break before lecturing commenters on "guessing about performance is perhaps the most frequent anti-pattern in all programming" next time :)

Re:TypeScript Is Surprisingly OK for Compilers by simlevesque on Friday August 18, 2023 @01:37PM (#37179248)
> Also, try/catch will never compile in the JIT

That's false. It used to be this way with Crankshaft but since 2017 we have Turbofan which solves this.

Re:TypeScript Is Surprisingly OK for Compilers by paddim8 on Friday August 18, 2023 @03:00AM (#37172199)
I would think C# is easier for this due to having proper (and very convenient) pattern matching.
Re:TypeScript Is Surprisingly OK for Compilers by zkldi on Friday August 18, 2023 @04:25AM (#37172755)
C# doesn't have anything resembling proper pattern matching. C#s pattern matching is akin to a marginally improved switch or if/else-if chain. C#s pattern matches aren't exhaustive, and the compiler doesn't properly check them at all.[0]

There are no proper sum types in C#, so 80% of the point isn't even there.

    enum Season
        {
        Spring,
        Summer,
        Autumn,
        Winter
    }
     
...

    int PatternMatch(Season season) =>
    season switch {
        Season.Spring => 1,
        Season.Summer => 2,
        Season.Autumn => 3,
        Season.Winter => 4,
        // compiler can't prove the above code is exhaustive because no proper sum types
        // compiler needs nonsensical branch here that diverges
        _ => throw new ArgumentException("Invalid enum value for command", nameof(command)),
    };
Re:TypeScript Is Surprisingly OK for Compilers by hardware2win on Friday August 18, 2023 @04:27AM (#37172764)
>compiler can't prove the above code is exhaustive because no proper sum types

Thats because c#s enum is not "closed"

https://github.com/dotnet/csharplang/issues/3179

Re:TypeScript Is Surprisingly OK for Compilers by paddim8 on Wednesday August 23, 2023 @02:26AM (#37232462)
These things are not about pattern matching but about other language features.
Re:TypeScript Is Surprisingly OK for Compilers by thebears5454 on Friday August 18, 2023 @02:45AM (#37172097)
Naively, I would have guessed it being harder than C#
Re:TypeScript Is Surprisingly OK for Compilers by IshKebab on Friday August 18, 2023 @03:21AM (#37172318)
> picked up most of the ML featureset

It really hasn't. In this very post he had to use a visitor to work around the fact that switch isn't an expression.

JavaScript's support for iterators is also weirdly shit. It has `.map()` but that only works on arrays. You can't map an iterator!

Re:TypeScript Is Surprisingly OK for Compilers by andyferris on Friday August 18, 2023 @03:32AM (#37172384)
I think there’s an iterator proposal out there for JS with generic map, filter, etc.
Re:TypeScript Is Surprisingly OK for Compilers by bakkoting on Friday August 18, 2023 @04:39PM (#37181783)
You can now! The iterator helpers proposal is stage 3 and shipping in Chrome.

  (new Set([0, 1, 2])).values().map(x => x + 1).toArray()
You can also reduce, filter, find, etc.
Re:TypeScript Is Surprisingly OK for Compilers by jillesvangurp on Friday August 18, 2023 @04:39AM (#37172850)
I've done a bit of typescript and kotlin-js. It always strikes me how close those two languages are. Yes there are lots of differences but they aren't that different and you can transition from one to the other pretty easily. I have my preferences (kotlin) but I can work with both.

IMHO typescript could just cut loose from its javascript compatibility. Why not compile it to wasm instead of transpiling it to javascript? Kotlin is in the process of adding a wasm compiler and they already have a js transpiler. The same code results in a lot smaller binaries and loads a lot faster in wasm form. Browser Javascript is not a great compilation target. And who cares what the minified crap that loads in the browser looks like? The only reason for backwards compatibility is allowing javascript projects to easily transition to typescript. But that's increasingly less relevant now that a lot of projects start out being typescript from day 1.

Of course, Assembly script is already a thing. But why not make that a bit more official? It wouldn't surprise me to see people doing a lot of web development in languages like that in a few years.

Re:TypeScript Is Surprisingly OK for Compilers by orra on Friday August 18, 2023 @04:54AM (#37172963)
I'm afraid that's wishful thinking. JS compatibility is core to the TypeScript ethos, regardless of TypeScript's own popularity.

Besides, enums (?) aside, and ignoring typechecking, compiling TS is really easy right now. Switching to WASM is a high ask.

Re:TypeScript Is Surprisingly OK for Compilers by horsawlarway on Friday August 18, 2023 @07:55AM (#37174429)
JS compatibility is core to Typescript's own popularity.
Re:TypeScript Is Surprisingly OK for Compilers by flohofwoe on Friday August 18, 2023 @05:32AM (#37173235)
"Modern" Javascript essentially is Typescript without the type hints (e.g. if you ignore the historical baggage, JS is actually a fairly decent language).
Re:TypeScript Is Surprisingly OK for Compilers by junon on Friday August 18, 2023 @05:50AM (#37173395)
I actually argue JS was a better language before all of the changes made, starting with const/let. The only thing I'd say makes sense are classes but the fact they aren't syntax sugar over prototypes was a mistake.

People wanted a different language, they should have gotten more scripting languages in the browser. Not changing JavaScript so much that it's no longer JavaScript.

Re:TypeScript Is Surprisingly OK for Compilers by flohofwoe on Friday August 18, 2023 @05:57AM (#37173456)
Coming into web development fairly recently (after 2013 or so) from the statically typed hemisphere and without closely following the Javascript history from the start I naturally cannot agree ;)

(things like the scoping rules for 'var' is just bizarre, same with the concept of 'prototypes')

Looking at typical "old-school" Javascript code gives me the creeps the same way as looking at K&R C code ;)

Re:TypeScript Is Surprisingly OK for Compilers by shrimpx on Friday August 18, 2023 @06:16AM (#37173617)
> aren't syntax sugar

They aren't syntactic sugar? Pretty sure `class Foo { blah() {} }` is equivalent to `function Foo() {}; Foo.prototype.blah = function() {}`.

Re:TypeScript Is Surprisingly OK for Compilers by bornfreddy on Friday August 18, 2023 @06:20AM (#37173641)
> the fact they aren't syntax sugar over prototypes was a mistake

Totally different meaning.

Re:TypeScript Is Surprisingly OK for Compilers by shrimpx on Friday August 18, 2023 @06:22AM (#37173652)
What else would 'syntax sugar over prototypes' mean?
Re:TypeScript Is Surprisingly OK for Compilers by zdragnar on Friday August 18, 2023 @10:15AM (#37175907)
There are a few very specific differences. In a subclass, 'this' doesn't exist until you call "super" for example, and the constructor will throw an error of invoked without the "new" keyword. [O]

These differences let you extend built-in things that simply can't be done with old prototype constructor syntax. [1]

[O] I should probably be using a more recent reference like MDN, but the 2ality series always sticks out in my mind whenever "just syntax sugar" comes up: https://2ality.com/2015/02/es6-classes-final.html#safety-che...

[1] https://2ality.com/2015/02/es6-classes-final.html#subclassin...

Re:TypeScript Is Surprisingly OK for Compilers by shrimpx on Friday August 18, 2023 @03:58PM (#37181260)
Thanks. It sounds like subclassing built-ins is where transpilers hit a hard wall. Other syntactic features of es6 can be transpiled.
Re:TypeScript Is Surprisingly OK for Compilers by zdragnar on Saturday August 19, 2023 @10:06AM (#37188913)
http://kangax.github.io/compat-table/es6/

This page lists features from es6 (and newer versions linked at the top) along with compliance to the spec. First column is the current browser, second is babel+corejs polyfills.

Overall, babel gets about 70% of the way there.

Re:TypeScript Is Surprisingly OK for Compilers by cxr on Friday August 18, 2023 @10:40AM (#37176302)
[delayed]
Re:TypeScript Is Surprisingly OK for Compilers by junon on Friday August 18, 2023 @11:38AM (#37177122)
They are not, no.
Re:TypeScript Is Surprisingly OK for Compilers by shrimpx on Friday August 18, 2023 @04:00PM (#37181298)
My example is incorrect because it doesn’t cover all the edge cases but you can desugar es6 to es5, except in es5 you can’t subclass builtins.
Re:TypeScript Is Surprisingly OK for Compilers by baq on Friday August 18, 2023 @06:10AM (#37173574)
you can still write the old javascript. it'll feel very lonely, though.
Re:TypeScript Is Surprisingly OK for Compilers by usrusr on Friday August 18, 2023 @07:42AM (#37174344)
Yeah, having just jumped into ts after a long js hiatus since back when The Good Parts was still surprising, it's quite awesome to see how much of what I assumed to be "ts stuff" is actually just postdeluvian js. Makes ts more attractive, not less. I do wonder however of it was possible to identify parts of that language superset that are fully redundant (as in not even required for exotic edge cases) and let loose some draconian linter?
Re:TypeScript Is Surprisingly OK for Compilers by jakubmazanec on Friday August 18, 2023 @09:28AM (#37175319)
Re:TypeScript Is Surprisingly OK for Compilers by usrusr on Friday August 18, 2023 @12:16PM (#37177826)
Sure, but that's still seems quite mix and match, anything goes, choose your own adventure. There are many positives about this approach, but as a learner a little more common ground between codebases would certainly be appreciated.
Re:TypeScript Is Surprisingly OK for Compilers by jakubmazanec on Saturday August 19, 2023 @10:46AM (#37189339)
True. I always thought that we should have additional mode stricter than https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe....
Re:TypeScript Is Surprisingly OK for Compilers by Kyro38 on Friday August 18, 2023 @05:52AM (#37173416)
> IMHO typescript could just cut loose from its javascript compatibility. Why not compile it to wasm instead of transpiling it to javascript

In browsers the Wasm runtime doesn't have access to the DOM APIs. So that's wishful thinking ATM.

Re:TypeScript Is Surprisingly OK for Compilers by jbreckmckye on Friday August 18, 2023 @06:36AM (#37173775)
> IMHO typescript could just cut loose from its javascript compatibility. Why not compile it to wasm instead of transpiling it to javascript?

My fantasy for the past year has been, if I could magically program anything, bringing a compiler and spec wholesale into the world out of the void, I would create a new language (call it WebScript as a placeholder) that

- featured an ML style type system, ADTs, a type syntax nearly indistinguishable from TypeScript

- whose actual core language essentially resembled Kotlin or "Go with exceptions"

- compiled to WASM or JS as a compatibility bridge

Nothing radical. Nothing revolutionary. Just these things would be an immediate plus.

But maybe AssemblyScript is a good enough step towards that.

Re:TypeScript Is Surprisingly OK for Compilers by jitl on Friday August 18, 2023 @07:41AM (#37174331)
Go has exceptions: you can use `panic` to throw/catch just fine. The community will bring out the torch and pitchforks because it’s “not idiomatic” but if you’re programming solo or with other pragmatists don’t let it stop you.
Re:TypeScript Is Surprisingly OK for Compilers by madeofpalk on Friday August 18, 2023 @11:41AM (#37177187)
Or just pass pointers because you need optionality, and get null pointer exceptions for free :)
Re:TypeScript Is Surprisingly OK for Compilers by skybrian on Friday August 18, 2023 @01:02PM (#37178627)
Does the community care if it’s not in a public API? If it’s caught within the same library it doesn’t affect anyone else.
Re:TypeScript Is Surprisingly OK for Compilers by andrewcobby on Friday August 18, 2023 @09:55AM (#37175661)
I’m actually working on a language like this. I quite liked ReScript/ReasonML, but having to manually write binding to use TypeScript or JS code is a drag. I’m making a functional language that looks and feels like TS and lets you import TS directly. Mostly just stripping imperative statements, removing class declaration and adding pattern matching and better data constructors (never liked the discriminated unions). WASM as a target is a bit further off.
Re:TypeScript Is Surprisingly OK for Compilers by srhtftw on Friday August 18, 2023 @03:56PM (#37181227)
I've been hoping to see alternative targets to JS for TS as well. WASM makes a lot of sense but TypeScriptToLua¹ also looks interesting.

1: https://typescripttolua.github.io

Re:TypeScript Is Surprisingly OK for Compilers by AgentME on Friday August 18, 2023 @07:02AM (#37173978)
Typescript is defined to run exactly as the equivalent Javascript you get when all the type declarations are stripped out of the source. There's no benefit in compiling it to WASM unless you had a WASM JS engine (or JS->WASM converter) that executed JS faster than the browser's built-in JS engine (or created WASM binaries that were smaller than compressed minified JS, which seems extra unlikely when you'd have to include a JS runtime). If that existed, browsers would just upgrade to use that internally on all JS.
Re:TypeScript Is Surprisingly OK for Compilers by hibbelig on Friday August 18, 2023 @08:51AM (#37174942)
Your parent suggested to make changes to TS so that TS is no longer compatible with JS (in the sense you described). Once that happens, compiling to WASM instead of transpiling to JS is a very valid design choice.
Re:TypeScript Is Surprisingly OK for Compilers by wiseowise on Friday August 18, 2023 @12:20PM (#37177895)
The whole purpose of TS is better JS.
Re:TypeScript Is Surprisingly OK for Compilers by AgentME on Friday August 18, 2023 @11:09PM (#37185088)
That's fair, though there have been several projects that have attempted to be "JS-ish but with some behavior changes with strict type handling sprinkled in for optimizations" like the Strong types proposal (cancelled) and Dart (which switched to being a compile to JS language just like Typescript), so I'm currently convinced that the trade-offs aren't obviously worth it and that it's unlikely Typescript will change its priorities in that direction in the near future.
Re:TypeScript Is Surprisingly OK for Compilers by 88913527 on Friday August 18, 2023 @03:30PM (#37180884)
You can't strip out enums. They're converted to integers in JavaScript.
Re:TypeScript Is Surprisingly OK for Compilers by xvilka on Friday August 18, 2023 @04:52AM (#37172944)
This is why once WebAssembly more polished and more common, languages like JS and TS could become obsolete since proper, more powerful languages will suddenly become a valid choice for Web.
Re:TypeScript Is Surprisingly OK for Compilers by flohofwoe on Friday August 18, 2023 @05:27AM (#37173198)
Any non-toy WASM application running in browsers will almost certainly end up as a hybrid WASM/JS application, just because you can't call directly from WASM into browser APIs, and even if the JS shim is "hidden from view", sometimes it's either more convenient or even more performant to write more than just a thin API shim in Javascript, especially for asynchronous code or to avoid redundant copying of large data blobs in and out of the WASM heap.
Re:TypeScript Is Surprisingly OK for Compilers by LudwigNagasena on Friday August 18, 2023 @06:06AM (#37173541)
> just because you can't call directly from WASM into browser APIs

Surely that will change someday.

Re:TypeScript Is Surprisingly OK for Compilers by flohofwoe on Friday August 18, 2023 @06:23AM (#37173673)
You are still limited by the fact that browser APIs are mainly designed for usage with Javascript, and those Javascript APIs usually don't map all that well to languages used with WASM (which typically use the "C ABI" for FFI). There is zero chance that each web API will get a second API which is compatible with "C calling conventions".

There is a (now inactive) "interface-types" proposal, which has dissolved into "component-types", but this scope-creep definitely is already quite concerning:

https://github.com/WebAssembly/interface-types

Re:TypeScript Is Surprisingly OK for Compilers by mbork_pl on Friday August 18, 2023 @05:23AM (#37173166)
You mean, like C and its derivatives became obsolete once successors to PDP machines were built? ;-)
Re:TypeScript Is Surprisingly OK for Compilers by andsoitis on Friday August 18, 2023 @08:52AM (#37174964)
> This is why once WebAssembly more polished and more common, languages like JS and TS could become obsolete since proper, more powerful languages will suddenly become a valid choice for Web.

JavaScript and TypeScript are not "proper" languages?

Different languages are powerful in different use case dimensions (tradeoffs), and the typical client-side web programming has a very very strong UI angle, which many "more powerful" languages that I am going to guess you have in mind are less adept at.

Re:TypeScript Is Surprisingly OK for Compilers by airstrike on Friday August 18, 2023 @09:32AM (#37175378)
JavaScript's redeeming quality is that it is ubiquitous due to being used by browsers. I don't think anybody credibly claims it to be a language we would want to use if we were to redesign web programming from scratch today
Re:TypeScript Is Surprisingly OK for Compilers by andsoitis on Friday August 18, 2023 @09:59AM (#37175698)
What follows is meant to be descriptive rather arguing "my camp is right".

> JavaScript's redeeming quality is that it is ubiquitous due to being used by browsers.

JavaScript has other properties that make it very adept at a wide range of web app usecases. Languages exist not in isolation, but have a dynamic environment w.r.t. domains they excel in, tooling, mindshare, programming in the small and the large, comlexity, etc.

> I don't think anybody credibly claims it to be a language we would want to use if we were to redesign web programming from scratch today

Dart has tried. Many languages transpile to JavaScript (and have for a long time).

Yet, JavaScript and TypeScript are some of the most popular languages on the planet.

If the web is still around in 20 years, it will be interesting to see whether another language has taken center stage. I'm not quite holding my breath, if only because even with transpilation being around for many many years, no other language has overtaken. I have a hard time seeing WASM changing that outcome in a meaningful way.

Re:TypeScript Is Surprisingly OK for Compilers by shepherdjerred on Friday August 18, 2023 @11:22AM (#37176862)
TypeScript is a pleasure to use. I have no desire to replace it with another language.
Re:TypeScript Is Surprisingly OK for Compilers by madeofpalk on Friday August 18, 2023 @11:50AM (#37177368)
Outside of the "everyone hates javascript" circle jerk, I really enjoy writing Typescript. I find its type system to be very natural and pleasent to use. It's my go-to for any generic task.
Re:TypeScript Is Surprisingly OK for Compilers by marcosdumay on Friday August 18, 2023 @12:35PM (#37178139)
> I don't think anybody credibly claims it to be a language we would want to use

Ouch, you posted this on the internet.

Somebody, somewhere is certainly going to claim this. Some of the people with that claim are even going to have a rationale behind it.

And to be fair, the tooling is going to push a lot of opinion. Because as bad as the JS/TS tooling is, its UI component has been evolving steadily while every other tool stagnated. And by now it has quite probably surpassed the 90's RAD paradigm (I mean, I can't make up my mind).

IMO, the language is one of the main things holding those tools back, but most people just won't agree.

Re:TypeScript Is Surprisingly OK for Compilers by thrashh on Friday August 18, 2023 @12:50PM (#37178422)
What language would that be?

I've programmed in Java, Python, C, C#, TypeScript, VHDL, and some other languages and they all fucking suck in some way.

If it was up to me, I would pick the best parts of the languages/ecosystems and make a Frankenstein language.

And anyway in the end, it's never the language. It's the ecosystem. Just because you can run Java on .NET doesn't mean you should -- because almost no one else does it your way and it's not worth the trouble maintaining some weird approach very few people use. You're never going to get help from library authors when it doesn't work on your weird setup.

Re:TypeScript Is Surprisingly OK for Compilers by pjmlp on Friday August 18, 2023 @04:53AM (#37172955)
C# and Swift have pattern matching.
Re:TypeScript Is Surprisingly OK for Compilers by troupo on Friday August 18, 2023 @04:57AM (#37172980)
It's more limited than what you'd ideally want: pattern matching in function definitions. This makes walking ASTs a breeze.

Edit: And inline pattern matching for values returned from expressions and function calls (similar to destructuring, but more powerful).

Re:TypeScript Is Surprisingly OK for Compilers by pjmlp on Friday August 18, 2023 @12:34PM (#37178121)
I would say what C#12 does is already quite good, likewise for Swift.

Perfection is the enemy from good.

Those I can use at work, ML derived languages not, even F# is an uphill battle in most shops.

Re:TypeScript Is Surprisingly OK for Compilers by chpatrick on Friday August 18, 2023 @05:34AM (#37173244)
Type-refining if in TypeScript is good enough for pattern matching if you ask me.
Re:TypeScript Is Surprisingly OK for Compilers by graftak on Friday August 18, 2023 @07:06AM (#37174030)
The TypeScript type system meta programming actually does pattern matching very well, it’s just the underlying JS runtimes that can’t, there is a proposal for it though; https://github.com/tc39/proposal-pattern-matching.
Re:TypeScript Is Surprisingly OK for Compilers by DrScientist on Friday August 18, 2023 @06:12AM (#37173588)
Re:TypeScript Is Surprisingly OK for Compilers by madeofpalk on Friday August 18, 2023 @11:39AM (#37177152)
Lack of pattern matching is annoying, but Typescript's tagged unions and type narrowing from if-statements are a good substitude and make for a very pleasent time traversing ASTs. C# has it's own way to express similar data structures (with subclasses and interfaces), but I find unions+narrowing much more natural in Typescript.
Re:TypeScript Is Surprisingly OK for Compilers by retrac on Friday August 18, 2023 @11:59AM (#37177534)
Some crude snippets from a Pascal-C (I never could decide) self-educational compiler/toy I wrote a while ago (in Haskell):

    -- a parser function that matches on { ... } returning ... 
    -- can be combined with other parsers 
    braces = (symbol "{") `between` (symbol "}") 
    ...
    -- a statement is a controlFlow or a declaration or an assignment
    statement = controlFlow <|> declaration <|> assignment

    -- a block is either 1 or more statements surrounded by { ... }
    -- or a single statement.
    block = (braces $ many statement) <|> statement
    ...
    -- An expression is a number, or a variable, or a binary operation
    -- derive functionality to print and test equality of these values.
    data Expr = 
        Num Int
      | Var Variable
      | DualOp Op Expr Expr
      ...
      deriving (Show, Eq)
    ...
    foldConstants (DualOp Add (Num a) (Num b)) = Num (a + b)
    ...
Parser combinators (parser functions that take other parser functions and return more complex combined parser functions) with enough syntactic sugar can express BNF-like grammars directly as code. And ML-style list and pattern matching operations are very expressive for operating on the intermediate representation.