News for hackers. Stuff that matters.
Re:Node.js adds experimental support for TypeScript by pansa2 on Thursday July 25, 2024 @12:32AM (#41064729)
If Node.js can run TypeScript files directly, then the TypeScript compiler won't need to strip types and convert to JavaScript - it could be used solely as a type checker. This would be similar to the situation in Python, where type checkers check types and leave them intact, and the Python interpreter just ignores them.

It's interesting, though, that this approach in Python has led to several (4?) different popular type checkers, which AFAIK all use the same type hint syntax but apply different semantics. However for JavaScript, TypeScript seems to have become the one-and-only popular type checker.

In Python, I've even heard of people writing types in source code but never checking them, essentially using type hints as a more convenient syntax for comments. Support for ignoring types in Node.js would make that approach possible in JavaScript as well.

Re:Node.js adds experimental support for TypeScript by dobladov on Thursday July 25, 2024 @04:02AM (#41066034)
You can have this now adding types with JSDoc and validating them with typescript without compiling, you get faster builds and code that works everywhere without magic or need to strip anything else than comments.

The biggest pain point of using JSDoc at least for me was the import syntax, this has changed since Typescript 5.5, and it's now not an issue anymore.

Re:Node.js adds experimental support for TypeScript by murmansk on Thursday July 25, 2024 @04:13AM (#41066120)
For god's sake, please stop shilling JSDoc as a TS replacement. It is not. If you encounter anything more complicated than `A extends B`, JSDoc is a pain in the ass of huge intensity to write and maintain.
Re:Node.js adds experimental support for TypeScript by adhamsalama on Thursday July 25, 2024 @04:20AM (#41066174)
You can write TypeScript types in JSDoc.
Re:Node.js adds experimental support for TypeScript by sureIy on Thursday July 25, 2024 @06:51AM (#41067055)
You can’t write complex TypeScript types in JSDoc, which is what GP said.

The moment you need to declare or extend a type you’re done, you have to do so in a separate .ts file. It would be possible to do so and import it in JSDoc, but as mentioned before it’s a huge PITA on top of the PITA that writing types can already be (e.g. function/callbacks/generics)

Re:Node.js adds experimental support for TypeScript by dobladov on Thursday July 25, 2024 @04:38AM (#41066289)
You should write complex types in interfaces files where they belong, and there's full typescript support.

I use this approach professionally in teams with many developers, and it works better for us than native TS. Honestly give it a try, I was skeptical at first.

Re:Node.js adds experimental support for TypeScript by rty32 on Thursday July 25, 2024 @06:51AM (#41067060)
In general JSDoc is just much more verbose and has more friction, even outside complex types. I recently finished a small (20 files/3000 lines), strictly typed JS project using full JSDoc, and I really miss the experience of using the real TypeScript syntax. Pain points: annotating function parameter types (especially anonymous function), intermediate variable type and automatic type-only import, these are the ones that I can remember. Yes you can get 99% there with JSDoc and .d.ts files, but that's painful.
Re:Node.js adds experimental support for TypeScript by dobladov on Thursday July 25, 2024 @09:38AM (#41068560)
I use snippets to write those, yes it's more verbose there's not denying that.

For me the advantages of just having JS files and not worrying about more complex source-maps, build files, etc definitely makes it worth it.

Re:Node.js adds experimental support for TypeScript by FractalHQ on Thursday July 25, 2024 @04:10PM (#41072832)
Source maps and build files are automatically generated when bundling which you need to do with or without typescript… so this argument always confuses me. There is no tangible downside in my experience.. either way it’s just typing “pnpm build”.
Re:Node.js adds experimental support for TypeScript by afavour on Thursday July 25, 2024 @07:54AM (#41067524)
I’ve had a lot of success combining JSDoc JS with .d.ts files. It’s kind of a Frankenstein philosophically (one half using TS and one half not) but the actual experience is great: still a very robust type system but no transpiling required.

In a world where ES modules are natively supported everywhere it’s a joy to have a project “just work” with zero build steps.

Re:Node.js adds experimental support for TypeScript by flanbiscuit on Thursday July 25, 2024 @04:02PM (#41072750)
I do this as well. JSDoc is great for simple definitions, but as soon as you want to do something more complicated (generics, operators, access types, etc) you get stuck. The .d.ts are ignored because you're only importing them within JSDoc comments.
Re:Node.js adds experimental support for TypeScript by Waterluvian on Thursday July 25, 2024 @08:36AM (#41067920)
Jsdoc is honestly fine for simple and smaller projects. But yeah, it’s definitely not nearly as expensive while being anywhere as succinct.
Re:Node.js adds experimental support for TypeScript by yard2010 on Thursday July 25, 2024 @12:18PM (#41070429)
JSDoc is for docs, TypeScript is a static type checker. How can these tools be used interchangeably?
Re:Node.js adds experimental support for TypeScript by styfle on Friday July 26, 2024 @11:10AM (#41079245)
You can configure tsconfig.json to read JSDoc and error on invalid types so that you effectively get the same behavior as writing typescript.
Re:Node.js adds experimental support for TypeScript by meiraleal on Thursday July 25, 2024 @09:32AM (#41068499)
Dude you are shilling adding a compile phase to a dynamic language and think that's smart! Stop telling people to not talk about JSDoc.
Re:Node.js adds experimental support for TypeScript by tracker1 on Thursday July 25, 2024 @11:06AM (#41069554)
JSDoc is also helpful in dealing with multiple argument option types for a function or constructor, which won't show in TS alone.
Re:Node.js adds experimental support for TypeScript by sroussey on Thursday July 25, 2024 @12:02PM (#41070230)
Re:Node.js adds experimental support for TypeScript by itsmeste on Thursday July 25, 2024 @05:54AM (#41066750)
I strongly agree, but JSDoc isn't "the cool thing". So it's left to be used by us, who care (and read their docs).
Re:Node.js adds experimental support for TypeScript by llimllib on Thursday July 25, 2024 @09:31AM (#41068484)
The auto-export of declared types was what killed it for me
Re:Node.js adds experimental support for TypeScript by epolanski on Thursday July 25, 2024 @08:40AM (#41067965)
JSDoc absolutely does not scale and allows for very limited type programming.

It's fine on toy projects, and somewhat I would say, for 99% of users that don't even know what a mapped or intersection type is.

Re:Node.js adds experimental support for TypeScript by mablopoule on Thursday July 25, 2024 @09:39AM (#41068565)
JSDoc does not scale, but some projects are just better when they aren't scaled.

JSDoc is indeed fine on toy project, or in fact any project (even prod-ready ones) that doesn't warrant the trouble of adding NPM packages and transpilation steps.

Although they are rare, those type of small, feature-complete codebases do exists.

Re:Node.js adds experimental support for TypeScript by eezing on Friday July 26, 2024 @01:48AM (#41076089)
Good for annotating js files here and there, but lousy dx.
Re:Node.js adds experimental support for TypeScript by winter_blue on Thursday July 25, 2024 @12:34AM (#41064736)
Flow (by Facebook) used to be fairly significant in the JavaScript several years ago, but right now it's somewhat clear that TypeScript has won rather handily.
Re:Node.js adds experimental support for TypeScript by mattnewton on Thursday July 25, 2024 @01:12AM (#41064927)
Before that there was the closure compiler (Google) which had type annotations in comments. The annotation syntax in comments was a little clunky but overall that project was ahead of it's time. Now I believe even inside google that has been transpiled to typescript (or typescript is being transpiled to closure, I can't remember which - the point is that the typescript interface is what people are using for new code).
Re:Node.js adds experimental support for TypeScript by btown on Thursday July 25, 2024 @02:17AM (#41065270)
Google’s Closure Library is fascinating too. It’s being retired, but if you want to build a rich text interface for email authoring that truly feels like Gmail, warts and all, you can just use a pre-compiled version of the library and follow https://github.com/google/closure-library/blob/master/closur... within a more modern codebase!
Re:Node.js adds experimental support for TypeScript by miki123211 on Thursday July 25, 2024 @01:51AM (#41065117)
Closure was also interesting because it integrated type checking and minification, which made minification significantly more useful.

With normal Javascript and typescript, you can't minify property names, so `foo.bar.doSomethingVeryComplicated()` can only be turned into `a.bar.doSomethingVeryComplicated()`, not `a.b.c()`, like with Closure. This is because objects can be indexed by strings. Something like `foo.bar[function]()` is perfectly valid JS, where the value of `function` might come from the user.

A minifier can't guarantee that such expressions won't be used, so it cannot optimize property accesses. Because Closure was a type checker and a minifier at the same time, it could minify the properties declared as private, while leaving the public ones intact.

Re:Node.js adds experimental support for TypeScript by wiktor-k on Thursday July 25, 2024 @02:34AM (#41065370)
> Something like `foo.bar[function]()` is perfectly valid JS,

A minor thing but `function` is a keyword in JS so technically it's not a "perfectly valid JS".

Re:Node.js adds experimental support for TypeScript by mkesper on Thursday July 25, 2024 @03:10AM (#41065635)
Oh boy, just think functionName and it fits.
Re:Node.js adds experimental support for TypeScript by mananaysiempre on Thursday July 25, 2024 @07:49AM (#41067475)
> A minifier can't guarantee that such expressions won't be used, so it cannot optimize property accesses.

Given TypeScript’s type system is unsound, neither could it even if it tried, right? I guess Flow could, but well, here we are.

Re:Node.js adds experimental support for TypeScript by afavour on Thursday July 25, 2024 @07:56AM (#41067538)
Theoretically TS could… until it encounters an ‘any’ type in that code path, then it would have to give up.

But there are TSconfig options to ensure no use of any so with the right level of strictness it could happen.

Re:Node.js adds experimental support for TypeScript by epolanski on Thursday July 25, 2024 @08:43AM (#41067996)
What do you mean by unsound exactly.

I'm asking because there's no accepted definition of what an unsound type system is.

What I often see is that the word unsound is used to mean that a type system can accept types different to what has been declared, and in that case there's nothing unsound about ts since it won't allow you to do so.

Re:Node.js adds experimental support for TypeScript by cstrahan on Thursday July 25, 2024 @10:51AM (#41069387)
> and in that case there's nothing unsound about ts since it won't allow you to do so

Consider this example (https://www.typescriptlang.org/play/?ssl=10&ssc=1&pln=1&pc=1...):

  function messUpTheArray(arr: Array<string | number>): void {
      arr.push(3);
  }
  
  const strings: Array<string> = ['foo', 'bar'];
  messUpTheArray(strings);
  
  const s: string = strings[2];
  console.log(s.toLowerCase())
  
Could you explain how this isn't the type system accepting types "different to what has been declared"? Kinda looks like TypeScript is happy to type check this, despite `s` being a `number` at runtime.
Re:Node.js adds experimental support for TypeScript by epolanski on Thursday July 25, 2024 @12:33PM (#41070583)
That's a good example, albeit quite of a far-fetched one.

In Haskell land, where the type system is considered sound you have `head` functions of type `List a -> a` that are unsound too, because the list might be empty.

Re:Node.js adds experimental support for TypeScript by crdrost on Thursday July 25, 2024 @02:06PM (#41071530)
That option also exists, you can just leave out the `messUpTheArray` lines and you get an error about how `undefined` also doesn't have a `.toLowerCase()` method.

However this problem as stated is slightly different and has to do with a failure of OOP/subtyping to actually intermingle with our expectations of covariance.

So to just use classic "animal metaphor" OOP, if you have an Animal class with Dog and Cat subclasses, and you create an IORef<Cat>, a cell that can contain a cat, you would like to provide that to an IORef<Animal> function because you want to think of the type as covariant: Cat is a subtype of Animal, F<Cat> should be a subtype of F<Animal>. The problem is that this function now has the blessing of the type system to store a Dog in the cell, which can be observed by the parts that still consider this an IORef<Cat>.

Put slightly differently, in OOP, the methods of IORef<Cat> all accept an implicit IORef<Cat> called `this`, if those methods are part of what define an IORef<x> then an IORef<x> is necessarily invariant, not covariant, in <x>. And then you can't assume subtyping. So to be sound a subtype system would presumably have to actually mark contra/covariance around everything, and TypeScript very intentionally documents that they don't do this and are just trying to make a "best effort" pass because JavaScript has 0 types, and crappy types are better than no types, and we can't wait for perfect types to replace the crappy types.

Re:Node.js adds experimental support for TypeScript by cstrahan on Thursday July 25, 2024 @06:00PM (#41073826)
> In Haskell land, where the type system is considered sound you have `head` functions of type `List a -> a` that are unsound too, because the list might be empty.

Haskell's `head` not is not an example of the type system being unsound (I stress this point because we've been talking about type system soundness, not something-else-soundness).

From the view of the type system, `head` is perfectly sound: if the list is empty, the resulting value is ⊥ ("bottom"). And ⊥ is an inhabitant of every type. Therefore, `head` returning ⊥ when given an empty list is perfectly fine. When you force ⊥ (i.e. use it any way whatsoever), an exception is thrown. See https://wiki.haskell.org/Bottom

This is very much not the same thing (or remotely analogous) to what we have in my TypeScript example. There, the code fails at runtime when I attempt to call `toLowerCase`, yes; what's worse is the slightly different scenario where we succeed in calling something we shouldn't:

  class Person {
    name: string;
   
    constructor(name: string) {
      this.name = name;
    }
   
    kill() {
      console.log("Killing: " + this.name);
    }
  }
  
  class Murderer extends Person { }
  
  class Innocent extends Person { }
  
  function populatePeopleFromDatabase(people: Array<Innocent | Murderer>): void {
      // imagine this came from a real SQL query
      people.push(new Innocent("Bob"));
  }
  
  
  function populateMurderersFromDatabase(people: Array<Murderer>): void {
      // TODO(Aleck): come back and replace this with a query that only selects murderers.
      //              i wanted to get the rest of the code in place, and this type checks,
      //              so I'll punt on this for now and come back later when I wrap my head
      //              around the proper SQL.
      //              we're not actually using this anywhere just yet, so no biggie ¯\_(ツ)_/¯
      populatePeopleFromDatabase(people);
  }
  
  // ... some time later, Bob comes along and implements the murderer execution logic:
  const murderers: Array<Murderer> = [];
  populateMurderersFromDatabase(murderers);
  // Bob is about to have a really shitty day:
  murderer.forEach((murderer) => murderer.kill());
It is not possible to write an analogous example in Haskell using `head`.
Re:Node.js adds experimental support for TypeScript by sharlos201068 on Thursday July 25, 2024 @10:48AM (#41069348)
That’s not correct, there’s several ways the actual type of a value differs from what typescript thinks it is. But soundness isn’t a goal of typescript.
Re:Node.js adds experimental support for TypeScript by WorldMaker on Thursday July 25, 2024 @11:19AM (#41069706)
It's maybe useful to note in this discussion for some that "soundness" of a type system is a bit of technical/theoretical jargon that in some cases has specific mathematical definitions and so "unsound" often sounds harsher (connotatively) than it means. The vast majority of type systems are "unsound" for very pragmatic reasons. Developers don't often care to work in a "sound" type systems. Some of the "most sound" type systems we've collectively managed to build are in things like theorem provers and type assertion systems that some of us don't always even consider useful for "real" software development.

Typescript is a bit more unsound than most because of the escape hatch `any` and because of the (intentional) disconnect between compiler and runtime environment. Even though "unsound" sounds like a bad thing to be, it's a big part of why Typescript is so successful.

Re:Node.js adds experimental support for TypeScript by price on Friday July 26, 2024 @03:36AM (#41076595)
There's nothing arcane or particularly theoretical about soundness. It means that if you have an expression of some type, and at runtime the expression evaluates to a value, the value will always be of that type.

For example if you have a Java expression of type MyClass, and it gets evaluated, then it must either throw (so that it doesn't produce any value) or produce a value of type MyClass: either an instance of MyClass, or of one of its subclasses, or null. It will never produce an instance of some other class, or an int, or anything else that isn't a valid value for the type MyClass.

In addition to helping human readers reason about the code, a sound type system is a big deal for a compiler: it makes it possible to compile the code AOT to fast native code, without inserting a bunch of runtime checks and dynamic dispatching to handle the fact that inevitably some of the types (but you don't know which) are wrong.

The compiler implications are what motivated the Dart language's developers to migrate from an unsound to a sound type system a few years ago: https://dart.dev/language/type-system#the-benefits-of-soundn... so that they could compile Flutter apps AOT. This didn't require anyone to make their code resemble what you'd do in a theorem prover — it just means that, for example, all casts are checked, so that they throw if the value doesn't turn out to have the type the cast wants to return.

TypeScript is unsound because when you have an expression with a type, that tells you nothing at all for sure about what the value of the expression can be — it might be of that type, or it might be anything else. It's still valuable because you can maintain a codebase where the types are mostly accurate, and that's enough to help a lot in reading and maintaining the code.

Re:Node.js adds experimental support for TypeScript by afiori on Friday July 26, 2024 @03:45AM (#41076626)
The key factor is that typescript is not a language, it is a notation system for a completely independent language.

The purpose of typescript is usefully type as much javascript as possible, to do both this and have a sound type system it would require to change javascript.

Re:Node.js adds experimental support for TypeScript by price on Friday July 26, 2024 @04:09AM (#41076755)
Definitely to get the most ergonomic programming experience, while also having a sound type system, you'd need to change some of the semantics of the language.

A prime example is that if you index into an array of type `T[]`, JS semantics mean the value you get back could be undefined as well as a `T`. So to describe existing JS semantics in a sound type system, the type would have to be `T | undefined`, which would be a big pain. Alternatively you could make the type `T`, but only if you make the runtime semantics be that an out-of-bounds access throws instead of returning undefined.

Re:Node.js adds experimental support for TypeScript by afiori on Friday July 26, 2024 @03:50AM (#41076651)
any and unknown are perfectly sound, if they were the only types then soundness would be automatic.

The problem is that you can arbitrarily narrow types (and any can narrow to any type) eg: https://www.typescriptlang.org/play/?#code/DYUwLgBAzg9grgOwC...

Re:Node.js adds experimental support for TypeScript by price on Friday July 26, 2024 @04:02AM (#41076727)
That's true but misleading: if "any" and "unknown" were the only types, then "any" would be indistinguishable from "unknown" and you'd really have just the one type. Which makes the type system sound because it doesn't say anything.

If your type system has at least two types that aren't the same as each other, then adding "any" makes it unsound right there. The essence of "any" is that it lets you take a value of one type and pretend it's of any other type. Which is to say that "any" is basically the purified form of unsoundness.

Re:Node.js adds experimental support for TypeScript by afiori on Friday July 26, 2024 @04:49AM (#41076940)
a typing of any cannot be unsound because it is always correct, narrowing any can be unsound.
Re:Node.js adds experimental support for TypeScript by mananaysiempre on Thursday July 25, 2024 @12:36PM (#41070615)
> there's no accepted definition of what an unsound type system is

Huh?

The cheeky answer would be that the definition here is the one the TypeScript documentation itself uses[1].

The useful answer is that there’s only one general definition that I’ve ever encountered: a type system is sound if no well-typed program encounters type errors during its execution. Importantly, that’s not a statement about the (static) type system in isolation: it’s tied to the language’s dynamic semantics.

The tricky part, of course, is defining “type error”. In theoretical contexts, it’s common to just not define any evaluation rules at all for outwardly ill-typed things (negating a list, say), thus the common phrasing that no well-typed program must get stuck (unable to evaluate further). In practical statically-typed languages, there are on occasion cases that are defined not to be type errors essentially by fiat, such as null pointer accesses in Java, or escape hatches, such as unsafeCoerce in practical implementations of Haskell.

Of course, ECMAScript just defines behaviour for everything (except violating invariants in proxy handlers, in which case, lol, good luck), so arguably every static type system for it is sound, even one that allows var foo: string = 42. Obviously that’s not a helpful point of view. I think it’s reasonable to say that whatever we count as erroneous situations must at the very least include all occurrences of ReferenceError and TypeError.

TypeScript prevents most of them, which is good enough for its linting use case, when the worst possible result is that a buggy program crashes. It would definitely not be good enough for Closure Compiler’s minification use case, when the worst possible result is that a correct program gets silently miscompiled (misminified?).

[1] https://www.typescriptlang.org/docs/handbook/type-compatibil...

Re:Node.js adds experimental support for TypeScript by RyanCavanaugh on Thursday July 25, 2024 @04:11PM (#41072853)
Flow's type system isn't sound either FWIW
Re:Node.js adds experimental support for TypeScript by price on Friday July 26, 2024 @03:51AM (#41076654)
Yeah, Flow had the ambition to be sound but has never accomplished it.

If you read the Flow codebase and its Git history, you can see that it's not for lack of trying, either — every couple of years there's an ambitious new engineer with a new plan for how to make it happen. But it's a real tough migration problem — it only works if they can provide a credible, appealing migration path to the other engineers across Facebook/Meta's giant JS codebase. Starting from a language like JS with all the dynamic tricks people use there, that's a tough job.

(And naturally it'd be even harder if they were trying to get any wider community to migrate, outside their own employer.)

Re:Node.js adds experimental support for TypeScript by RyanCavanaugh on Friday July 26, 2024 @07:37PM (#41083291)
Flow doesn't even check that array access is in-bounds, contrast to TypeScript with noUncheckedIndexedAccess on. They're clearly equally willing to make a few trade-offs for developer convenience (a position I entirely agree with FWIW)
Re:Node.js adds experimental support for TypeScript by price on Friday July 26, 2024 @09:19PM (#41083807)
Neat example, thanks! I hadn't known TS had that option. Array access was actually exactly the example that came to mind for me in a related discussion: https://news.ycombinator.com/item?id=41076755

I wonder how widely used that option is. As I said in that other comment, it feels to me like the sort of thing that would produce errors all over the place, and would therefore be a real pain to migrate to. (It'd be just fine if the language semantics were that out-of-bounds array access throws, but that's not the semantics JS has.) I don't have a real empirical sense of that, though.

Re:Node.js adds experimental support for TypeScript by kevincox on Thursday July 25, 2024 @10:45AM (#41069300)
> it could minify the properties declared as private, while leaving the public ones intact.

I don't think it ever actually did this. It renamed all properties (you could use the index syntax to avoid this) and just used a global mapping to ensure that every source property name was consistently renamed (no matter what type it was on). I don't think type information was ever actually used in minification.

So if you had two independent types that had a `getName` function the compiler would always give them the same minified name even though in theory their names could be different because they were fully independent types. The mapping was always bijective. This is suboptimal because short names like `a` could only be used for a single source name, leading to higher entropy names overall. Additionally names from the JS runtime were globally excluded from renaming. So any `.length` property would never be renamed in case it was `[].length`.

Re:Node.js adds experimental support for TypeScript by AprilArcus on Thursday July 25, 2024 @11:15AM (#41069658)
of course this created an interoperability nightmare with third party libraries, which irrevocably forked Google's whole JS ecosystem from the community's 20 years ago and turned their codebases into a miserable backwater.
Re:Node.js adds experimental support for TypeScript by antifa on Friday July 26, 2024 @07:48AM (#41077825)
Teaser has a mangle props feature. The mangle props by exact name or pattern has worked for me, but it might affect library objects or browser built-ins that I definitely don't want it to, but I've not gotten the mangle all props of this object version of it to work.
Re:Node.js adds experimental support for TypeScript by LoganDark on Thursday July 25, 2024 @01:17AM (#41064952)
Oh, Closure Compiler is such a throwback. I still remember staring at the project page on Google Code. Isn't it like two decades old or even older by this point? Is it still alive?
Re:Node.js adds experimental support for TypeScript by flohofwoe on Thursday July 25, 2024 @02:38AM (#41065405)
Closure is still used in Emscripten to optimize the generated Javascript shim file.
Re:Node.js adds experimental support for TypeScript by mdhb on Thursday July 25, 2024 @01:34AM (#41065035)
The compiler itself lives on but it works with TypeScript now rather than the JSDoc comments style approach which is officially EOL AFAIK.
Re:Node.js adds experimental support for TypeScript by rty32 on Thursday July 25, 2024 @07:00AM (#41067122)
This can give you some hints of the current status of closure compiler:

https://github.com/google/closure-compiler/issues/2731

I happen to know this because we have some old projects that depend on this and are working hard to get rid of the dependency.

I wish Google either updates it or just mark the whole thing deprecated -- the world has already moved on anyway. Relating this to Google's recent cost cutting, and seeing some other Google's open source projects more or less getting abandoned, I have to say that today's Google is definitely not the same company from two decades ago.

Re:Node.js adds experimental support for TypeScript by rty32 on Thursday July 25, 2024 @06:54AM (#41067083)
Closure is almost a forgotten child of Google now. Does not even fully support ES2022 as of today. We are working hard to get rid of it completely. Surprise, lots of important projects still rely on it today.
Re:Node.js adds experimental support for TypeScript by jazzypants on Thursday July 25, 2024 @11:41AM (#41069953)
This is true. For instance, React still uses Closure compiler in their build process.
Re:Node.js adds experimental support for TypeScript by simplify on Thursday July 25, 2024 @08:22AM (#41067783)
Facebook never gave Flow enough resources, whereas Microsoft has had 10+ devs on TypeScript for a long time.
Re:Node.js adds experimental support for TypeScript by sesm on Thursday July 25, 2024 @11:44AM (#41069989)
Because Flow is an actual developer tool, not a rent-seeking landgrab with a marketing budget.
Re:Node.js adds experimental support for TypeScript by 9dev on Thursday July 25, 2024 @03:25PM (#41072390)
I don’t know what axe you have to grind, but TypeScript is firmly in the hands of the community now. There’s not much Microsoft could do to change that. In what way would it be rent-seeking?
Re:Node.js adds experimental support for TypeScript by recursive on Thursday July 25, 2024 @05:10PM (#41073433)
If you're paying rent for typescript, you're doing it wrong.
Re:Node.js adds experimental support for TypeScript by hajile on Thursday July 25, 2024 @10:15AM (#41068933)
Flow tries to be sound and that makes it infinitely better than TS where the creators openly threw the idea of soundness out the window from the very beginning.
Re:Node.js adds experimental support for TypeScript by ahuth on Thursday July 25, 2024 @11:00AM (#41069478)
TS made the choice to be “just JS” + types, and lean into JS-isms.

Both choices are reasonable ones to make. Flow has some really cool stuff, and works great for a lot of people.

There’s no denying, though, that there’s TS has done something right (even if you personally dislike it)

Re:Node.js adds experimental support for TypeScript by idlephysicist on Thursday July 25, 2024 @11:44AM (#41069992)
Can you explain what you mean when you say "to be sound"?
Re:Node.js adds experimental support for TypeScript by pansa2 on Thursday July 25, 2024 @11:55AM (#41070125)
Here's an example of TypeScript failing to be sound - it should give a type error but it doesn't. I believe Flow does indeed give a type error in this situation:

https://news.ycombinator.com/item?id=41069695

Re:Node.js adds experimental support for TypeScript by recursive on Thursday July 25, 2024 @05:10PM (#41073425)
You don't have to go even that far to find unsoundness in flow.

    const arr = ["abcd"];
    const str = arr[1];
    const num = str.length; // this throws
    console.log(num);
For me, typescript is a pretty good balance.
Re:Node.js adds experimental support for TypeScript by fabiospampinato on Thursday July 25, 2024 @06:42PM (#41074225)
Wait, so Flow is not actually sound and their website is lying? Or do they have some "technically correct" definition of "sound" that takes stuff like that into account?
Re:Node.js adds experimental support for TypeScript by recursive on Thursday July 25, 2024 @06:48PM (#41074272)
I have no idea about the lawyerly technicalities, but you can try it yourself to verify what I'm saying.

https://flow.org/try/

Compare these two programs.

    const arr = ["abcd"];
    const str = arr[1];
    const num = str.length; // this throws at runtime

    const arr = [new Date];
    const dt = arr[1];
    const num = dt.length; // fails to type check
Re:Node.js adds experimental support for TypeScript by hajile on Thursday July 25, 2024 @08:47PM (#41074956)
Even haskell will generate a runtime error for an out-of-bounds index

    main = putStrLn (["a", "b", "c"]!!4)
Re:Node.js adds experimental support for TypeScript by recursive on Thursday July 25, 2024 @09:41PM (#41075180)
This is different. Neither flow, typescript, nor javascript generate a runtime error for an out of bounds index. It's explicitly allowed by the language.

The result of the an OOB access of an array is specified to be `undefined`. The throw only happens later when the value is treated as the wrong type.

I don't consider a runtime error to be a failure of the type system for OOB array access. But in javascript, it's explicitly allowed by specification. It's a failure of any type system that fails to account for this specified behavior in the language.

Re:Node.js adds experimental support for TypeScript by hajile on Friday July 26, 2024 @09:23AM (#41078444)
> It's explicitly allowed by the language.

This is like arguing that a null exception is fine because it's allowed by the language. If you get `undefined` when you expect another type, most future interaction are guaranteed to have JS throw because of the JS equivalent of a null pointer exception. They are technically different because a dynamic language runtime can prevent a total crash, but the effect on your web app is going to be essentially the same.

    [1,2,3][4].toFixed(2)
> It's a failure of any type system that fails to account for this specified behavior in the language.

Haskell has the ability to handle the error.

How do you recommend a compiler to detect out-of-bounds at compile time? It can certainly do this for our trivial example, but that example will also be immediately evident the first time you run the code too, so it's probably not worth the effort. What about the infinite number of more subtle variants?

Re:Node.js adds experimental support for TypeScript by recursive on Friday July 26, 2024 @10:31AM (#41078932)
> How do you recommend a compiler to detect out-of-bounds at compile time?

I wouldn't make the recommendation that they do at all. Full soundness is not my thing. But... if Flow wanted to do it, it would have to change the type of indexing into `(Element[])[number]` with a read from `Element` to `Element | undefined`.

Re:Node.js adds experimental support for TypeScript by price on Friday July 26, 2024 @04:16AM (#41076784)
Flow is not sound. They have the ambition of trying to be sound (which I appreciate), but they've never accomplished it.

I went looking for where on their website they claim to be sound. There's definitely some misleading wording here: https://flow.org/en/docs/lang/types-and-expressions/#toc-sou... but if you read the whole section, it ends up also acknowledging that it's not entirely sound.

Re:Node.js adds experimental support for TypeScript by hajile on Thursday July 25, 2024 @08:46PM (#41074955)
I think this is not a very good example. Not only does it also throw in TS, but it even throws in Haskell which is pretty much the poster boy for sound type systems.

This isn't a type error unless your type system is also encoding lengths, but most type systems aren't going to do that and leave it to the runtime (I suspect the halting problem makes a general solution impossible).

    main = putStrLn (["a", "b", "c"]!!4)
Re:Node.js adds experimental support for TypeScript by recursive on Thursday July 25, 2024 @09:38PM (#41075153)
Yes it throws in typescript. Typescript isn't the the language chasing soundness at any cost. This just illustrates the futility of chasing soundness.

Soundness is good as long as the type-checking benefit is worth the cost of the constraints in the language. If the poster child for soundness isn't able to account for this very simple and common scenario, then nothing will actually be able to deliever full soundness.

It's just a question of how far down the spectrum you're willing to go. Pure js is too unsound for my taste. Haskell is too constrained for my taste. You might come to a different conclusion, but for me, typescript is a good balance.

Re:Node.js adds experimental support for TypeScript by hajile on Friday July 26, 2024 @09:11AM (#41078334)
My balance point is StandardML. SML and TS both have structural typing (I believe this is why people find TS to be more ergonomic). SML has an actually sound type system (I believe there is an unsoundness related to assigning a function to a ref, but I've never even seen someone attempt to do that), but allows mutation, isn't lazy, and allows side effects.

Put another way, SML is all the best parts of TS, but with more soundness and none of the worst parts of TS and non of the many TS edge cases baked into the language because they keep squashing symptoms of unsoundness or adding weird JS edge cases that you shouldn't be doing anyway.

Re:Node.js adds experimental support for TypeScript by recursive on Friday July 26, 2024 @03:57PM (#41081726)
Personally, I think javascript kind of sucks, but it's approximately* the only choice for targeting browsers. If it wasn't for this face, I probably never would have touched TS. SML sounds pretty good.
Re:Node.js adds experimental support for TypeScript by price on Friday July 26, 2024 @03:10AM (#41076462)
When a language's type system is sound, that means that if you have an expression with type "string", then when you run the program the expression's value will only ever be a string and never some other sort of value.

Or stated more abstractly: if an expression has type T, and at runtime the expression evaluates to a value v, then v has type T.

The language can still have runtime errors, like if you try to access an array out of bounds. The key is that such operations have to give an error — like by throwing, so that the expression doesn't evaluate to any value at all — rather than returning a value that doesn't fit the type.

Both TypeScript and Flow are unsound, because an expression with type "string" can always turn out to evaluate to null or a number or an object or anything else. Flow had the ambition to be sound, which is honorable but they never accomplished it. TypeScript announced up front that they didn't care about soundness: https://www.typescriptlang.org/docs/handbook/type-compatibil...

Soundness is valuable because it makes it possible to look at the types and reason about the program using them. An unsound type-checker like TypeScript or Flow can still be very useful to human readers if most of the types in a codebase are accurate, but you always have to keep that asterisk in the back of your head.

One very concrete consequence of soundness that it makes it possible to compile the code to fast native code. That's what motivated Dart a few years ago to migrate from an unsound type system to a sound one: https://dart.dev/language/type-system so that it could AOT-compile Flutter apps for speed.

Re:Node.js adds experimental support for TypeScript by machiaweliczny on Thursday July 25, 2024 @10:25AM (#41069037)
But in practice is was crap
Re:Node.js adds experimental support for TypeScript by dwb on Thursday July 25, 2024 @12:22PM (#41070470)
This is a point in Flow's favour. However! Seven years ago or so, when TypeScript was quite young and seemed inferior to Flow in almost all respects, I chose Flow for a large project. Since then, I spent inordinate amounts of time updating our code for the latest breaking Flow version, until one came along that would have taken too long to update for, so we just stayed on that one. We migrated to TypeScript a little while back and the practical effect has been much more and effective type checking through more coverage and support. TypeScript may be unsound, but it works better over all. We turn on the vast majority of the safety features to mitigate the unsoundness. And it's developed by a team that are beholden to a large and vibrant user base, so any changes are generally well-managed. There's no contest, really.
Re:Node.js adds experimental support for TypeScript by hajile on Friday July 26, 2024 @09:02AM (#41078277)
Turning on EVERY safety feature won't mitigate the unsoundness because the problem goes beyond stuff like `any`.
Re:Node.js adds experimental support for TypeScript by dwb on Friday July 26, 2024 @10:09AM (#41078794)
I know, but it just doesn't matter enough. Believe me, I'm signed up to the idea of theoretical rigour, the argument for soundness is part of what originally won me over (along with previous good experiences with Flow on a smaller project, and the support for gradual adoption). I will continue to be drawn to languages and tools that have a strong theoretical foundation. But in this particular case, today, when comparing these particular projects in the large JavaScript codebase I am talking about, TypeScript still wins by some distance. I promise that it has caught way more errors and been more generally helpful in its language server abilities than Flow ever was. Maybe Flow has caught up since then in its core functionality, I haven't been keeping track, but there would still be the wide disparity in community support which has serious implications for developer education, availability of library type definitions, etc.
Re:Node.js adds experimental support for TypeScript by hajile on Friday July 26, 2024 @10:45AM (#41079040)
I think the real answer is adding actually sound types to JS itself.

One of the biggest revolutions in JS JITS was the inline cache (IC). It allows fast lookup and specialized functions (which would be too expensive otherwise). These in turn allow all the optimizations of the higher-tier JITs.

The biggest problem of Flow and TS is encouraging you to make slow code. The second you add a generic to your function, you are undoubtedly agreeing that it is going to be accepting more than 4 types. This means your function is megamorphic. No more IC. No more optimization (even worse, if it takes some time to hit those 5+ types, you get the dreaded deoptimization). In theory, they could detect that your function has 80 possible variations and create specialized, monomorphic functions for each one, but that's way too much code to send over the wire. That kind of specialization MUST be done in the JIT.

If you bake the types into the language via a `"use type"` directive, this give a LOT of potential. First, you can add an actually sound type system. Second, like `"use strict"` eliminated a lot of the really bad parts of JS, you can eliminate unwanted type coercion and prevent the really dynamic things that prevent optimization. Because the JIT can use these types, it can eliminate the need for IC altogether in typed functions. It can still detect the most-used type variants of a function and make specialized versions then use the types to directly link those call sites to the fast version for even more optimization.

I use TS because of its ubiquity, but I think there's the possibility for a future where a system a little more like Flow gets baked into the language.

Re:Node.js adds experimental support for TypeScript by dwb on Friday July 26, 2024 @11:29AM (#41079446)
Maybe! I see where you're coming from. That sounds like a long and painful road, still, though, from what is still a very dynamic language. Do you have a rough idea of how much more time/space-efficient a typical JavaScript program could be through this?
Re:Node.js adds experimental support for TypeScript by hajile on Friday July 26, 2024 @12:52PM (#41080148)
It's an interesting question.

JS uses a JIT while Ocaml is AOT which is generally an advantage for Ocaml.

Ocaml only compiles once while JS compiles every time it runs. This means that JS is a lot more selective about its compilation, but the hot code could be every bit as fast as Ocaml. On the flip side, Ocaml is fast because it compiles method-at-a-time and a SML compiler like MLton which does a slow whole-program pass can generate significantly faster code (despite being a part-time hobby project for a few academics).

The big difference is money. Ocaml has some funding, but nothing compared to JS. It's hard to believe, but handling strings in JS is probably faster than what most devs could do themselves in C/C++. It's not because JS is inherently faster. It's because those bits are native and have had countless man-years poured into making them fast. That said, even the JIT itself is top-tier and raw integer code is only 20-50% slower than C (excluding any SIMD optimizations).

I think the upper limit for a typed JS could be about as fast and maybe a little faster than Ocaml on the JIT and maybe even a little faster with a more restrictive subset compiling to WASM.

Re:Node.js adds experimental support for TypeScript by sprkv5 on Friday July 26, 2024 @01:27PM (#41080460)
> I use TS because of its ubiquity, but I think there's the possibility for a future where a system a little more like Flow gets baked into the language.

Have you looked into ReScript? It is basically a sound type system + JavaScript-like syntax. It inherits the type system from OCaml. You might like it. They recently released version 11.

Re:Node.js adds experimental support for TypeScript by sesm on Thursday July 25, 2024 @11:39AM (#41069935)
There was no real competition, Flow was a practical internal tool with 0 marketing budget. Typescript is typical MS 3E strategy with a huge budget. Needless to say, Flow is much more practical and less intrusive, but marketing budget captured all the newbie devs.
Re:Node.js adds experimental support for TypeScript by ignoramous on Thursday July 25, 2024 @11:57AM (#41070159)
> There was no real competition

There was: Anders Hejlsberg and Lars Bak: TypeScript, JavaScript, and Dart https://www.youtube.com/watch?v=5AqbCQuK0gM (2013).

Summary: https://g.co/gemini/share/a60c3897bae1 / https://archive.is/qJ1wA

Re:Node.js adds experimental support for TypeScript by com2kid on Thursday July 25, 2024 @02:31PM (#41071818)
TypeScript was really really easy to get started with back in the day. It allows for incremental correctness, has good docs, and good tooling. On top of that a lot of beginner React tutorials started out with TypeScript, which onboarded a lot of new engineers to the TS ecosystem, and got them used to the niceties of TS (e.g. import syntax).
Re:Node.js adds experimental support for TypeScript by treflop on Thursday July 25, 2024 @08:22PM (#41074843)
Have to disagree. I tried Flow irrespective of marketing and didn’t think it was polished. Kept running into type situations that the language didn’t support well. Kept bugging out in my IDE. Had no elegance.
Re:Node.js adds experimental support for TypeScript by spoiler on Friday July 26, 2024 @03:30AM (#41076563)
When I last used it, as a type system it was much better than TypeScript. A lot of flow features now exist in TypeScript though too.

One big annoyance with Flow I had is like you said: unpolished tooling. Another was frequent breaking changes (I don't hold it against them too much, it was 0.x software after all)

Also because features diverged, you had to maintain type defs for multiple versions of flow for for multiple library versions. And then at one point, they also decided to convert internal errors to any types instead of displaying the error. That was the last straw for me, especially since I maintained a few flow type defs. I spent _so_ much of _my_ time just on type def maintenance for open source libraries already, with the any decay I like flying blind too. So I just switched to TS with its interior type system: it was good enough and others maintained library typedefs for me. But now the type systems are much more closely aligned (unless flow drifted), so switching to TS paid off in the end.

Re:Node.js adds experimental support for TypeScript by Doxin on Thursday July 25, 2024 @02:21AM (#41065301)
> In Python, I've even heard of people writing types in source code but never checking them, essentially using type hints as a more convenient syntax for comments.

Note that there's IDEs that'll use type hints to improve autocomplete and the like too, so even when not checking types it can make sense to add them in some places.

Re:Node.js adds experimental support for TypeScript by phartenfeller on Thursday July 25, 2024 @01:41AM (#41065075)
There is an EcmaScript proposal to go in that direction: https://github.com/tc39/proposal-type-annotations

I think this should be part of the language spec.

Re:Node.js adds experimental support for TypeScript by wiseowise on Thursday July 25, 2024 @02:44AM (#41065439)
Beyond ugly. They should just make TS official and be done with it.

E: I thought it was JSDoc proposal. Ignore the comment.

Re:Node.js adds experimental support for TypeScript by blovescoffee on Thursday July 25, 2024 @03:12AM (#41065652)
I did only briefly look at the proposal. What did you find so ugly?
Re:Node.js adds experimental support for TypeScript by wiseowise on Thursday July 25, 2024 @03:33AM (#41065824)
I misread the proposal. Thought it was for JSDoc.
Re:Node.js adds experimental support for TypeScript by meiraleal on Thursday July 25, 2024 @09:38AM (#41068554)
Misread no, you didn't read.
Re:Node.js adds experimental support for TypeScript by wiseowise on Thursday July 25, 2024 @10:47AM (#41069331)
Yeah. I saw JSDoc and closed it, lol.
Re:Node.js adds experimental support for TypeScript by Dylan16807 on Thursday July 25, 2024 @02:39PM (#41071924)
Specifically, you saw the section titled "Limits of JSDoc Type Annotations"?
Re:Node.js adds experimental support for TypeScript by wiseowise on Thursday July 25, 2024 @03:22PM (#41072360)
Specifically, I saw JSDoc syntax and it triggered me so much that I closed the page and threw my phone away in disgust at absurdness of even the idea that someone thought having something like this unironically is a remotely good idea.
Re:Node.js adds experimental support for TypeScript by FractalHQ on Thursday July 25, 2024 @04:12PM (#41072854)
I support this behavior as the only correct reaction.
Re:Node.js adds experimental support for TypeScript by padavanchik on Thursday July 25, 2024 @03:10AM (#41065638)
There is no language spec for TS. No alternative implementations. All we have is checker.ts. It's ugly and slow.
Re:Node.js adds experimental support for TypeScript by IshKebab on Thursday July 25, 2024 @03:09AM (#41065627)
What do you mean ugly? This basically is making Typescript official.

They just can't have browsers doing the actual type checking because there isn't a specification for how to do that, and writing one would be extremely complicated, and I'm not sure what the point would be anyway.

Re:Node.js adds experimental support for TypeScript by wiseowise on Thursday July 25, 2024 @03:34AM (#41065831)
I misread the proposal, tho it it was for JSDoc.
Re:Node.js adds experimental support for TypeScript by pphysch on Thursday July 25, 2024 @12:38AM (#41064760)
> In Python, I've even heard of people writing types in source code but never checking them

This is my main approach. Type hints are wonderful for keeping code legible/sane without going into full static type enforcement which can become cumbersome for rapid development.

Re:Node.js adds experimental support for TypeScript by josephg on Thursday July 25, 2024 @12:57AM (#41064851)
You can configure typescript to make typing optional. With that option set, you can literally rename .js files to .ts and everything "compiles" and just works. Adding this feature to nodejs means you don't even have to set up tsc if you don't want to.

But if I were putting in type hints like this, I'd still definitely want them to be statically checked. Its better to have no types at all than wrong types.

Re:Node.js adds experimental support for TypeScript by pansa2 on Thursday July 25, 2024 @01:33AM (#41065034)
> Its better to have no types at all than wrong types.

I agree - but the type systems of both Python and TypeScript are unsound, so all type hints can potentially be wrong. That's one reason why I still mostly use untyped Python - I don't think it's worth the effort of writing type annotations if they're just going to sit there and tell lies.

Or maybe the unsoundness is just a theoretical issue - are incorrect type hints much of a problem in practice?

Re:Node.js adds experimental support for TypeScript by zoul on Thursday July 25, 2024 @01:49AM (#41065106)
In my experience unsoundness is almost never a problem in practice, see here for details:

https://effectivetypescript.com/2021/05/06/unsoundness/

Re:Node.js adds experimental support for TypeScript by hajile on Thursday July 25, 2024 @03:35PM (#41072495)
Unsound types are never a problem until they are at which point you are staring at code that SHOULD be working, but is somehow breaking.
Re:Node.js adds experimental support for TypeScript by lolinder on Thursday July 25, 2024 @01:49AM (#41065108)
I've been using TypeScript professionally for 6+ years and have only ever run into issues at the border between TypeScript and other systems (usually network, sometimes libraries that don't come with types). There are a few edge cases that I'm aware of, but they don't really come up in practice.
Re:Node.js adds experimental support for TypeScript by kcrwfrd_ on Thursday July 25, 2024 @02:05AM (#41065199)
Is this “unsound”-ness that you’re referring to because it uses structural typing and not nominal typing?

Fwiw I’ve been working with TypeScript for 8+ years now and I’m pretty sure wrong type hints has never been a problem. TS is a God-send for working with a codebase.

Re:Node.js adds experimental support for TypeScript by nyssos on Thursday July 25, 2024 @09:35AM (#41068522)
There's not much connection. Typescript's record types aren't sound, but that's far from its only source of unsoundness, and sound structural typing is perfectly possible.
Re:Node.js adds experimental support for TypeScript by lolinder on Thursday July 25, 2024 @09:44AM (#41068617)
Soundness is also a highly theoretical issue that I've never once heard a professional TypeScript developer express concern about and have never once heard a single anecdote of it being an issue in real-world code that wasn't specifically designed to show the unsoundness. It usually only comes up among PL people (who I count myself among) who are extremely into the theory but not regularly coding in the language.

Do you have an anecdote (just one!) of a case where TypeScript's lack of type system soundness bit you on a real application? Or an anecdote you can link to from someone else?

Re:Node.js adds experimental support for TypeScript by kcrwfrd_ on Thursday July 25, 2024 @12:14PM (#41070379)
Ah someone else posted a link and I understand the unsoundness now.

The only time an issue ever came up for me was in dealing with arrays

  let foo: number[] = [0, 1, 2]

  // typed as number but it’s really undefined
  let bar = foo[3]
But once you’re aware of the caveat it’s something you can deal with, and it certainly doesn’t negate the many massive benefits that TS confers over vanilla JS.
Re:Node.js adds experimental support for TypeScript by lolinder on Thursday July 25, 2024 @12:46PM (#41070718)
Yeah, that example is unsound in the same way that Java's type system is unsound, it's a compromise nearly all languages make to avoid forcing you to add checks when you know what you're doing. That's not the kind of problem that people usually are referring to when they single out TypeScript.
Re:Node.js adds experimental support for TypeScript by AfterAnimator on Tuesday July 30, 2024 @09:25AM (#41108951)
For this case, I've switched to using `foo.at(3)` now instead, as it returns `T | undefined`, so you have to handle the undefined case.
Re:Node.js adds experimental support for TypeScript by nyssos on Thursday July 25, 2024 @01:36PM (#41071247)
> Do you have an anecdote (just one!) of a case where TypeScript's lack of type system soundness bit you on a real application?

Sure. The usual Java-style variance nonsense is probably the most common source, but I see you're not bothered by that, so the next worst thing is likely object spreading. Here's an anonymized version of something that cropped up in code review earlier this week:

    const incomingValue: { name: string, updatedAt: number } = { name: "foo", updatedAt: 0 }

    const intermediateValueWithPoorlyChosenSignature: { name: string } = incomingValue

    const outgoingValue: { name: string, updatedAt: string } = { updatedAt: new Date().toISOString() , ...intermediateValueWithPoorlyChosenSignature }
Re:Node.js adds experimental support for TypeScript by lolinder on Thursday July 25, 2024 @03:40PM (#41072556)
I mean... yes, there's a footgun there where you have to know to spread first and then add the new properties. That's just a good practice in the general case: an intermediate type that fully described the data wouldn't have saved you from overwriting it unless you actually looked closely at the type signature.

And yes, TypeScript types are "at least these properties" and not "exactly these properties". That is by design and is frankly one reason why I like TypeScript over Java/C#/Kotlin.

I'd be very interested to know what you'd do to change the type system here to catch this. Are you proposing that types be exact bounds rather than lower bounds on what an object contains?

Re:Node.js adds experimental support for TypeScript by haskman on Friday July 26, 2024 @04:58AM (#41076979)
Look into "Row types" and how PureScript, Haskell, and Elm (to a limited extent) do it.

'{foo :: Int | bar} is a record with a known property 'foo' and some unspecified properties 'bar'. You cannot pass a `{foo :: Int, bar :: Int}` into a function that expects `{foo :: Int}`.

A function that accepts any record with a field foo, changes foo, keeping other properties intact has the type

    {foo :: Int | bar} -> {foo :: Int | bar}
Re:Node.js adds experimental support for TypeScript by nyssos on Friday July 26, 2024 @07:32AM (#41077741)
> That's just a good practice in the general case: an intermediate type that fully described the data wouldn't have saved you from overwriting it unless you actually looked closely at the type signature.

The issue isn't that it got overridden, it's that it got overridden with a value of the wrong type. An intermediate type signature with `updatedAt` as a key will produce a type error regardless of the type of the corresponding value.

> I'd be very interested to know what you'd do to change the type system here to catch this.

Like the other commenter said, extensible records. Ideally extensible row types, with records, unions, heterogeneous lists, and so on as interpretations, but that seems very unlikely.

Re:Node.js adds experimental support for TypeScript by cstrahan on Thursday July 25, 2024 @11:18AM (#41069695)
No, TypeScript is not unsound because it uses structural typing.

A language has a sound type system if every well-typed program behaves as defined by the language's semantics during execution.

Go is structurally typed, and yet it is sound: code that successfully type checks is guaranteed to abide the semantics of the language.

TypeScript is unsound because code that type checks does not necessarily abide the semantics of the language:

  function messUpTheArray(arr: Array<string | number>): void {
      arr.push(3);
  }
  
  const strings: Array<string> = ['foo', 'bar'];
  messUpTheArray(strings);
  
  const s: string = strings[2];
  console.log(s.toLowerCase())
`strings` is declared as a `Array<string>`, but TypeScript is happy to insert a `number` into it. This is a contradiction, and an example of unsoundness.

`s` is declared as `string`, but TypeScript is happy to assign a `number` to it. This is a contradiction, and an example of unsoundness.

This code eventually fails at runtime when we try to call `s.toLowerCase()`, as `number` has no such function.

What we're seeing here is that TypeScript will readily accept programs which violate its own rules. Any language that does this, whether nominally typed or structurally typed, is unsound.

Re:Node.js adds experimental support for TypeScript by jaggederest on Thursday July 25, 2024 @01:06AM (#41064900)
Yeah I start projects by explicitly typing `any` all over the place and gradually refining things, so every type that's specified is explicit and checked, I'm really enjoying that style.
Re:Node.js adds experimental support for TypeScript by crabmusket on Thursday July 25, 2024 @01:52AM (#41065119)
Combine this with an eslint config that nudges you about explicit any, and the typescript compiler option to disallow implicit any, and you're well taken care of.
Re:Node.js adds experimental support for TypeScript by black3r on Thursday July 25, 2024 @04:50AM (#41066362)
Or you can configure the TS compiler to allow JS imports, then everything also compiles and works, but you can slowly convert your codebase from JS to TS file by file and be sure that all TS files are properly typed and all JS files are untyped instead of having everything as TS files where some are typed and some are not.
Re:Node.js adds experimental support for TypeScript by Humphrey on Thursday July 25, 2024 @01:30AM (#41065021)
Exactly. And if you use a library that does lots of meta programming (like Django) then it's impossible to pass all type errors. Hopefully one day the type system will be powerful enough to write a Django project with passing tests.
Re:Node.js adds experimental support for TypeScript by pansa2 on Thursday July 25, 2024 @01:25AM (#41064992)
With this approach, do you still use Python's standard syntax for type hints?

    def mersenne(p: int): return 2**p - 1
Or, given there's no need for the type hints to be checker-friendly, do you make them more human-friendly, e.g:

    def mersenne(p: 'prime number'): return 2**p - 1
Re:Node.js adds experimental support for TypeScript by LordKeren on Friday July 26, 2024 @09:44AM (#41078612)
While it’s not common (from the source code I’ve reviewed over the years), some people make a new type with a name and use that in the definition:

```

from typing import NewType

# Create a new type for some_prime SomePrime = NewType('SomePrime', int)

def process_prime(value: SomePrime) -> int: return value ```

However, this isn’t nearly as common as simply using a more descriptive argument name like “prime_number : int”

One of the big advantages to type hinting in Python is that it feeds the IDE a lot of information to increase auto-complete functionality, so you want to avoid things like p:”prime number”

Re:Node.js adds experimental support for TypeScript by pansa2 on Friday July 26, 2024 @11:57AM (#41079668)
> One of the big advantages to type hinting in Python is that it feeds the IDE a lot of information to increase auto-complete functionality

Yeah, until this discussion I thought the main benefit of type hints was earlier detection of bugs via static checking. Now though, I'm getting the impression that the bigger benefit is enabling IDE features such as autocomplete.

That helps me understand better why I haven't found type hints as useful as others seem to - I don't use an IDE. My use of Python is limited to small scripts which I write in a simple text editor.

Re:Node.js adds experimental support for TypeScript by LordKeren on Friday July 26, 2024 @12:36PM (#41079990)
There’s a fair argument to make that better IDE autocomplete does prevent many type-related issues even before a static type checker is run
Re:Node.js adds experimental support for TypeScript by edflsafoiewq on Thursday July 25, 2024 @08:11AM (#41067684)
IME if you aren't checking them, they're eventually going to be out of date.
Re:Node.js adds experimental support for TypeScript by rlt on Thursday July 25, 2024 @03:43PM (#41072580)
I don't find TypeScript to be burdensome when rapidly iterating. Depending on how you've configured your dev environment you can just ignore type errors and still run the code.
Re:Node.js adds experimental support for TypeScript by black3r on Thursday July 25, 2024 @04:40AM (#41066307)
> If Node.js can run TypeScript files directly, then the TypeScript compiler won't need to strip types and convert to JavaScript

Node.JS isn't the only JS runtime. You'll still have to compile TS to JS for browsers until all the browsers can run TS directly. Although some bundlers already do that by using a non-official compiler, like SWC (the one Node's trying out for this feature).

> In Python, I've even heard of people writing types in source code but never checking them, essentially using type hints as a more convenient syntax for comments.

It's not just comments. It's also, like the name "type hint" suggests, a hint for your IDE to display better autocomplete options.

Re:Node.js adds experimental support for TypeScript by pansa2 on Thursday July 25, 2024 @05:24AM (#41066589)
> It's not just comments. It's also a hint for your IDE to display better autocomplete options.

Ah yes, autocomplete is another benefit of machine-readable type hints. OTOH there's an argument that another IDE feature, informational pop-ups, would be better if they paid more attention to comments and less to type hints:

https://discuss.python.org/t/a-more-useful-and-less-divisive...

Re:Node.js adds experimental support for TypeScript by schwartzworld on Friday July 26, 2024 @04:22AM (#41076826)
Incidentally, this is how the ecmascript proposal for introducing types to JS would work by default. The runtime would ignore the types when running code. If you want type checking, you’d have to reach for external tooling.