4 ms·
The compiler can't help you at all when reading and validating data at runtime. You mean you could use a library that helps you with checking the shapes?
by beders 3y ago
The compiler can't help you at all when reading and validating data at runtime.
You mean you could use a library that helps you with checking the shapes?
- r3trohack3r 3y agoThe compiler will tell you when you are accessing data you haven't validated yet. Using the json-types module above, you assign your incoming json object to the JsonObject type. Then you type narrow by validating the payload contains the properties you are using. So you can: const user = (await body.json()) as JsonObject; // This is properly type narrowed and will work if (typeof user.emailAddress === "string") { // do something with user.emailAddress } // The compiler will let you know you can't trust // user.name to be a string at this point. This // would have generated an exception at runtime // for a malformed payload if the compiler didn't // catch it. user.username.split(" ") // You can also do type narrowing with early returns if(typeof user.age !== number) { return new Error("user.age is expected to be a number"); } // You can now use user.age with type safety ```