3 ms·
Good call. I love TypeScript, and wouldn't build a web app of even small scope without a typing solution at least as good as TypeScript, and it's the best. But
by spir 8y ago
Good call. I love TypeScript, and wouldn't build a web app of even small scope without a typing solution at least as good as TypeScript, and it's the best.
But, as you say, pattern matching sum types is a weak point in practical use of TypeScript.
Since the types only exist at compile time, maybe there could be a heavier opt-in system that uses something like Symbols to do pattern matching:
matchable type Shape = Circle | Square | Triangle;
const myShape: Shape;
match myShape {
// uses symbol magic under the hood, eg. if (SymbolShapeCircle in o)
case (c: Circle) { ... }
case (other: Triangle | Square) { ... }
}
- adrice727 8y agoIt's a far cry from actual pattern matching, but you can always tag your types[1]: interface Tagged { tag: string; } interface Circle extends Tagged { tag: 'circle' } // ... Other implementations switch (myShape.tag) { case 'circle': { // Do circular things } // etc . . . } You'll occasionally even see this in Scala code, since the @switch annotation optimizes pattern-match statements[2]. 1. https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions https://www.typescriptlang.org/docs/handbook/advanced-types.... 2. https://www.scala-lang.org/api/2.12.x/scala/annotation/switch.html https://www.scala-lang.org/api/2.12.x/scala/annotation/switc...