3 ms·
Typescript's exhaustiveness checking can be kind of clunky sometimes, particularly if you have a switch statement that's just causing side effects and not retur
by DylanSp 2y ago
Typescript's exhaustiveness checking can be kind of clunky sometimes, particularly if you have a switch statement that's just causing side effects and not returning a value. Last time I looked at it, I think you had to add a default case with some sort of dummy statement assigning a value to a variable with type `never`; while that's doable, the ergonomics are a bit annoying.
- yen223 2y agoI recall having to add that dummy 'never' branch in the past, but I haven't had to do that in newer projects on recent versions of Typescript.
- DylanSp 2y agoI just tried it in the online playground. I didn't get any sort of error with one of the cases unhandled. https://www.typescriptlang.org/play/?noFallthroughCasesInSwitch=true&q=115#code/C4TwDgpgBAKglgWzgOwOYFEBuFnCgXigG8pkBDBCALigCIBnYMgJ2FoG4oBXeiZgZSasIAExoAjAPaSANhDLIoAXygAfYqQrU6AYxmTeIjlBFdmZYHEnIayLgnF9l7AFBud1xlAAWCkXKwcPEIACghsXBp4JDRA3ABKAgA+YhcoKHoAdzhgHW8oMIjgADpySkSiNPSoHTJeOkYWNioq6prPPBQcuAtRACEQAFVeZgIocKDinj5BJtFXNvSPZHpZCGL9VBCuy16RAeG+eIXF8WZ5AGtXVqgAeluauuhaPQNRWha2++rlr0tKehgBRjCa4YqmcyWawndLfdJnS4nJQuJSuIA https://www.typescriptlang.org/play/?noFallthroughCasesInSwi...
- yen223 2y agoHmm. I think this is because in that situation, all cases (including the unhandled one) are "correctly" returning undefined. I can see that if I made the branch return a string, Typescript will correctly show the "Not all code paths return a value" error
- DylanSp 2y agoYep, or if you declare an explicit return type for the function, TS correctly gives a "Function lacks ending return statement and return type does not include 'undefined'." error. But if you have a function that's purely side-effecting, I think you still have to do something manual.