Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

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

[question] ZodType with ZodObject props #1495

Closed
domosedov opened this issue Oct 15, 2022 · 3 comments
Closed

[question] ZodType with ZodObject props #1495

domosedov opened this issue Oct 15, 2022 · 3 comments

Comments

@domosedov
Copy link

Hello, how create zodtype with object props from external types?

// Generated type from API
type User = {
 id: number
 name: string
}

const UserSchema = z.ZodType<User> = z.object({
  id: z.number(),
  name: z.string()
})

UserSchema.pick  // not working
// Property 'pick' does not exist on type 'ZodType<User, ZodTypeDef, User>'.
@suhaotian
Copy link

suhaotian commented Oct 15, 2022

type User = {
  id: number;
  name: string;
};

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
});

type USER = z.infer<typeof UserSchema>;

2022-10-15 at 11 09 PM

@nicolapalavecino
Copy link

Maybe you are looking to construct a validation object (z.object(...)) with a type. I believe that's not possible because of the compile time/run time limitations. I suppose you are looking something like this:

// Generated type from API
type User = {
  id: number;
  name: string;
};

const UserSchema: z.ZodObject<any, any, any, User> = z.object({
  id: z.number(),
  name: z.string(),
});

UserSchema.pick; // now it works

@domosedov
Copy link
Author

domosedov commented Dec 6, 2022

Modern solution TS 4.9+

type User = {
    id: number
    name: string
    age: number
}

const UserSchema = z.object({
    id: z.number(),
    name: z.string(),
    age: z.number()
}) satisfies z.ZodType<User>

Repository owner locked and limited conversation to collaborators Jan 14, 2023
@JacobWeisenburger JacobWeisenburger converted this issue into discussion #1886 Jan 14, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants