Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference incorrectly sets all fields as optional by default #43

Closed
pierreis opened this issue May 3, 2020 · 6 comments
Closed

Comments

@pierreis
Copy link
Contributor

pierreis commented May 3, 2020

Zod version: 1.5.0
TS version: 3.8.3

The type inference does not seem to be working properly, making all values of objects to be optional by default.

Let me take this code derived from the readme:

import * as z from "zod";

const dogSchema = z.object({
  name: z.string(),
  neutered: z.boolean(),
});

type T = z.TypeOf<typeof dogSchema>;  // -> { name?: string, neutered?: boolean }

const dog: T = {};  // -> Compiles without error

The expected behavior would be a compilation error deriving from name and neutered to be required.

@pierreis pierreis changed the title Type inference not working properly Type inference incorrectly sets all fields as optional by default May 3, 2020
@colinhacks
Copy link
Owner

You have to use Zod with strict mode. This wasn't clear from the README - my bad. Just add "strict": true in your tsconfig's "compilerOptions" and it'll work properly.

@mkreuzmayr
Copy link

Also be sure to NOT set "strictNullChecks": false in your tsconfig.json, because this would also result in all properties being infered as optional.

@mihanizm56
Copy link

mihanizm56 commented Jan 3, 2022

strict and strictNullChecks both true
tsc in the project is 4.5.2
node 14.18
gatsby 4
zod: 3.11.6

also all fields are optional

moreover - any primitive type and array of promite types work fine but not object

@scotttrinh
Copy link
Collaborator

@mihanizm56

Make sure your IDE or editor setup is properly getting your tsconfig.json, that's a common cause of that issue.

@bauti-defi
Copy link

bauti-defi commented Nov 22, 2022

strict and strictNullChecks both true
tsc in the project is 4.8.2
node 16.16.0
zod: 3.19.1

Using VScode. I have restarted the IDE multiple times. All my object field types are still being inferred as optional.


Edit: Seems to be VSCode problem...

@KevinEdry
Copy link

KevinEdry commented Jun 23, 2023

strict and strictNullChecks both true tsc in the project is 4.8.2 node 16.16.0 zod: 3.19.1

Using VScode. I have restarted the IDE multiple times. All my object field types are still being inferred as optional.

Edit: Seems to be VSCode problem...

how did you fix this?

edit:
I thinks adding this to my tsconfig.json did the trick:
"exactOptionalPropertyTypes": true,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

7 participants