Validate the Type of an User Input in TypeScript
Updated at
TypeScript is great as it allows us to handle types in a javascript environment. However, it is more like a linter and will not fail if you encounter mismatches in types in runtime.
Let us say that you have a server that accepts a body but expects it to be in a specific type. How can you ensure that this type is matched?
Runtime Type Validation
We are not the first devs that face type validation as an issue within the typescript realm. Therefore, there are already some solutions out there, that allow you to validate types at runtime.
Keep in mind that this comes at cost of resource utilization at runtime. It is not a free feature but requires some compute power. It is also not considered to be very fast, but it should match the needs of most commercial applications out there.
Using Zod
One well known library for type validation at runtime is called zod.
You can install it via: npm install zod.
Additionally, you should configure your typescript project to use strict mode by modifying your tsconfig.json:
0{1 "compilerOptions": {2 "strict": true3 }4}
It allows you to define schemas that you can validate an object against:
0import {z} from "zod";12const UserSchema = z.object({3 username: z.string(),4});56// throws an error on failure7UserSchema.parse({username: "Ludwig"});89// throws no error on failure but returns a status10UserSchema.safeParse({username: "Ludwig"});1112type User = z.infer<typeof UserSchema>;13// { username: string }
This allows you to use a standardized approach of creation types and including length checks, regex checks and much more on fields.
You can also customize error messages, which becomes quite handy if you use this approach with a form library like react-hook-forms
0const UserSchema = z.object({1 username: z.string().min(5, { message: "Must be 5 or more characters long" }),2});
I hope this article helped you 🚀