4 ms·
> type guard Thanks for the link, I am currently doing something similar without knowing TS implicit behavior. With 1st given example in the link, I forced on
by jjakque 7y ago
> type guard
Thanks for the link, I am currently doing something similar without knowing TS implicit behavior.
With 1st given example in the link, I forced on a style to such:
```
function doSomething(x: number | string) {
if (typeof x === 'string') {
doSomethingForString(x)
}
// Never do catch all to assume all non-strings are numbers
if (typeof x === 'number') {
doSomethingForNumber(x)
}
// Per transpiler rule, you not meant to be here, so error throwing is appropriate
throw new Error('Unexpected type')
}
function doSomethingForString(x: string) {
// Code
}
function doSomethingForNumber(x: number) {
// Code
}
```