3 ms·
I didn't see it mentioned, so how do you handle generating type-guards/run-time type validation functions?
by joshAg 5y ago
I didn't see it mentioned, so how do you handle generating type-guards/run-time type validation functions?
- bichiliad 5y agoIn general, TypeScript allows us to write code without worrying about run-time validation — if something says it's a string, we can trust it to be a string. However, this assumption falls apart at the edges between our typed and our untyped code. This is why we left in propTypes in our React style guide components, even though they were made redundant by TypeScript's own types. Can you elaborate a bit more about what sorts of type-guards and run-time validation functions you're thinking about? The only type-guards we somewhat generate are the ones Redux Toolkit makes for all of its actions, but aside from that, we only really use type guards when we're interfacing with a 3rd party API or something.
- joshAg 5y agoSure, so anytime you read JSON from a file or receive it from a network call, somewhere in the stack you're running JSON.parse() on it to turn the JSON string into the javascript object/primitive (or when you pull in data from a db). What happens if that object isn't what you think it should be? So like, if you've got an endpoint that says it returns interface Foo { baz: string bar: number } What happens if the endpoint actually sends you '{"bar":"23"}' ? How do you check to make sure the 'unverified' data is actually what you think it is? Or if the db schema has a nullable column but the typescript type for some reason isn't nullable/optional? Or worse, the db query isn't pulling the fields it should be (eg the db schema changed but the typescript definition didn't).