3 ms·
You can easily write your own "type guard functions" when you think TS is missing an inference from a runtime check you would like. The syntax is simple enough,
by WorldMaker 6y ago
You can easily write your own "type guard functions" when you think TS is missing an inference from a runtime check you would like. The syntax is simple enough, it's just a slightly different return type from boolean:
function isThing(value: unknown): value is Thing {
return typeof value === 'object' && typeof value.name === 'string'
}
The `unknown` type in general is still pretty new, but will be greatly helpful for cleaning up a lot of code that assumes a type or used to use `any` or `{}` because there wasn't a better type to use in that situation. The Typescript team is hesitant to change the last few cases of `any` in lib.d.ts to `unknown` directly (such as `JSON.parse`) because that would be a big compatibility breaking bug. There was a proposal for a flag to do that (treat `any` as `unknown` in lib.d.ts), but I'm not currently aware of whatever happened to that idea. I would love to see it or something like it happen.
- madeofpalk 6y agoUser-defined typeguards are just fancy ‘as string’. They are not type safe.
- benrbray 6y agoThey localize all the unsafe type casts to one place, where you can inspect the logic, though. Much better than having `as string` sprinkled throughout your code.