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

[Feature request] Reverse type inference #3244

Closed
rChaoz opened this issue Feb 16, 2024 · 1 comment
Closed

[Feature request] Reverse type inference #3244

rChaoz opened this issue Feb 16, 2024 · 1 comment

Comments

@rChaoz
Copy link

rChaoz commented Feb 16, 2024

First of all, I really love Zod! I tried a few validation libraries and Zod by far clicked with me the most. I especially love the TypeScript integration and how easy it is to create a pair of type/interface and validator (schema).

I think it would be amazing if (I'm not sure if this is implemented yet, I haven't found something similar) it would be possible to to reverse type inference. Something like this:

interface MyType {
    firstName: string
    lastName: string
    age: number
    whatever?: boolean
}

const myTypeSchema = z.fromType<MyType>({
    firstName: z.string(),
    // error: lastName is missing
    age: z.string(), // error: invalid type
    extra: z.number() // error: extra
})

This would make using the library much easier if you already have a bunch of existing interfaces, especially if you cannot modify them. Basically, an equivalent of z.object<T> but instead of having an argument schema: T it would have an argument schema: reverseInfer<T>.

I currently use this pretty bad hack because I will never understand types in TypeScript, why are they even turning complete:

({} as MyType) satisfies z.infer<typeof myTypeSchema>
({} as z.infer<typeof myTypeSchema>) satisfies MyType

This throws type errors if the schema isn't defined correctly.

@JacobWeisenburger
Copy link
Contributor

Is this what you are looking for?

interface MyType {
    firstName: string
    lastName: string
    age: number
    whatever?: boolean
}

const myTypeSchema = z.object( {
    firstName: z.string(),
    lastName: z.string(),
    age: z.number(),
    extra: z.number(),
} ) satisfies z.Schema<MyType>

If you found my answer satisfactory, please consider supporting me. Even a small amount is greatly appreciated. Thanks friend! 🙏
https://github.com/sponsors/JacobWeisenburger

Repository owner locked and limited conversation to collaborators Feb 17, 2024
@JacobWeisenburger JacobWeisenburger converted this issue into discussion #3253 Feb 17, 2024

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Projects
None yet
Development

No branches or pull requests

2 participants