
Matthew C.
—You are using Zod, the TypeScript-first schema validation library, in a project that uses TypeScript and wondering why Zod makes schema fields optional.
For example, you are using it to validate data structure from a login form. You’ve created an object schema for the expected structure of the user input data:
const UserSchema = z.object({ username: z.string(), password: z.string(), }); type User = z.infer<typeof UserSchema>;
You expect all of the fields to be required, but when you look at the TypeScript type of the UserSchema, you see that the object properties are optional:
type User = { username?: string; password?: string; };
This is unexpected as Zod makes all properties in an object schema required by default.
Enable strict mode in your project’s tsconfig.json file and make sure that you are using TypeScript version 4.5+:
{ "compilerOptions": { "strict": true } }
Enabling strict mode is a best practice for all TypeScript projects.
The strict flag adds extra type checks. Setting it to true enables all the strict mode family options, which includes the strictNullChecks option.
Note that if you have strictNullChecks set to true in your tsconfig.json file, all properties in your Zod object schemas will be optional even if strict is set to true. You can turn off strictNullChecks by setting it to false:
strictNullChecks: false,
This turns off the strictNullChecks strict mode family check, but not the other strict mode family options. When strictNullChecks is set to false, null and undefined are ignored by TypeScript, leading to unexpected errors at runtime.
It’s best to set it to true as it gives null and undefined their own distinct types, which can help you find and prevent bugs: you’ll get a type error if you try to use null or undefined where a value is expected.
If you can’t change the strict mode or strictNullChecks flags, you can use the Zod min() validation method for each object value to make sure a value is added:
const UserSchema = z.object({ username: z.string().min(1), password: z.string().min(1) });
You may have strict mode set to false for various reasons such as:
To enable strict mode in your project, gradually turn it on by adding each strict mode family option one by one:
strictNullChecksstrictFunctionTypesstrictBindCallApplystrictPropertyInitializationnoImplicitAnynoImplicitThisalwaysStrictTasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.
