News for hackers. Stuff that matters.
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.