Closed UchihaYuki closed 2 months ago
import { z } from 'zod';
const User = z .object({ username: z.string(), }) .strict();
User.parse({ username: "Ludwig" });
type User = z.infer
use strict instead of required
import { z } from 'zod';
const User = z .object({ username: z.string(), }) .strict();
User.parse({ username: "Ludwig" });
type User = z.infer; // expected { username: string }
use strict instead of required
The result is the same.
The code I pasted is from the official doc. The actual result is different from what doc says.
const User = z .object({ username: z.string().required(), })
Is that more what you want? Making the username key value required. Not just the object itself.
const User = z .object({ username: z.string(), }) .required();
User.parse({ username: "Ludwig" });
type User = z.infer
; // actual { username?: string } // expected { username: string }
required only exists on object. https://zod.dev/?id=required
The username property shouldn't be optional according to the doc, even if I just use z.object(). https://zod.dev/?id=basic-usage
Hi, if any combination of typescript and zod versions works for you, please let me know, I've been stuck here for 1 day now.
··· // tsconfig.json { // ... "compilerOptions": { // ... "strict": true } } ··· The solution!
Also "strictNullChecks"
must be set to true.
Please add this to documentation, because some frameworks ship with with "strictNullChecks": false,
··· // tsconfig.json { // ... "compilerOptions": { // ... "strict": true } } ··· The solution!
I have strict
and strictNullChecks
both set to true
yet I'm still having this issue. My required properties are still optional on my parsed data.
@colin-oos this is configuration, that works for me
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}
typescript version: Version 5.5.3 zod version: 3.23.8