top | item 38565496

(no title)

rogerclark | 2 years ago

TypeScript only has "discriminated unions" in an extremely busted form. While they are encoded in its type system, there is little support in control flow. Exhaustiveness checking is essentially optional: it's enabled in switch statements by either `assertNever` in the `default` case, or by limiting your function return from within switch cases with the `strictNullChecks` option enabled.

Without a match expression and first-class exhaustiveness checking, discriminated unions are far less useful. Of course, this is because they don't want the TypeScript compiler to actually generate code, so they can't add runtime features. While TypeScript is better than no TypeScript, it seems like a massive waste to build a compiler and then shy away from making people's lives easier when possible.

discuss

order

preommr|2 years ago

> it's enabled in switch statements by either `assertNever` in the `default` case, or by limiting your function return from within switch cases with the `strictNullChecks` option enabled.

What's wrong with using if statements?

```

if(shape.key === 'rectangle'){}

else if (shape.key === 'circle') {}

else {x: never = shape} // todo: use exhaustiveCheck(x: never)

```

That's pretty clear and easy.