(no title)
amake | 3 months ago
type Foo = 'foo' | 'bar';
const myFoo: Foo = 'foo';
switch (myFoo) {
case 'foo':
// do stuff
break;
default:
myFoo satisfies never; // Error here because 'bar' not handled
}
mckirk|3 months ago
jstanley|3 months ago
Klaster_1|3 months ago
mquander|3 months ago
rezonant|3 months ago
ervine|3 months ago
your_fin|3 months ago
It also makes match expressions an expression rather than a statement, so it can replace awkward terenaries. And it has no transitive dependencies!
[1]: https://github.com/gvergnaud/ts-pattern
inlined|3 months ago
Previously you could define a function that accepted never and throws. It tells the compiler that you expect the code path to be exhaustive and fixes any return value expected errors. If the type is changed so that it’s no longer exhaustive it will fail to compile and (still better than satisfies) if an invalid value is passed at runtime it will throw.
preommr|3 months ago
But unfortunately, using a default clause creates a branching condition that then treats the entire switch block as non-exhaustive, even though it is technically exhaustive over the switch target. It still requires something like throwing an exception, which at that point you might as well do 'const x: never = myFoo'.
nikeee|3 months ago
Normal_gaussian|3 months ago
klinch|3 months ago