by spir · 8y ago · 0 comments
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) { ... }
} 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....
2. https://www.scala-lang.org/api/2.12.x/scala/annotation/switc...