News for hackers. Stuff that matters.
Re:Rewriting TypeScript in Rust? You'D have to be by goto11 on Thursday December 15, 2022 @11:10AM (#34001644)
The pattern I'm most familiar with is using type constructors:

   type Shape = Square Int | Circle Int
and then pattern matching:

   print (Square size) = ..
   print (Circle radius) = ...
In Typescript this would be something like:

   type Shape = { type: 'square', size: number } | { type: 'circle', radius: number }
And string matching for type narrowing:

   function print(shape: Shape) {
     if (shape.type === 'square) {
       ...
     } else if (shape.type === 'square) {
      ...
     }
   }
The TypeScript approach is comparatively weird and verbose but also pretty clever since it doesn't require any change to the core language.

It also have some pitfalls, e.g. you can write:

  print({type: 'square', size: 10});
But you cant write:

  const x = {type: 'square', size: 10};
  print(x); <-- type error
You have to write:

  const x = {type: 'square' as const, size: 10};
  print(x);
Things like this just complicates the type system and type inference.

There are no comments on this comment yet.