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

proper mechanism to integrate with 3rd party types #52

Closed
cdaringe opened this issue May 17, 2020 · 5 comments
Closed

proper mechanism to integrate with 3rd party types #52

cdaringe opened this issue May 17, 2020 · 5 comments

Comments

@cdaringe
Copy link

cdaringe commented May 17, 2020

problem

import { Bananas } from '@fruit/banana'
import * as z from 'zod'
const schema = z.object({
  apple: z.string(),
  banana: z.doSomethingWith3pType() // z.object({}) ??
})
const myType = z.infer<typeof schema> // { apple: string, banana: ???? }

what the best way to get my 3p schema in? assuming because types have been compiled away, getting my 3p schema may not be possible, but, is there a mechanism to put my type into the schema, and get it reflected back out?

@colinhacks
Copy link
Owner

colinhacks commented May 17, 2020

I suppose I could implement a generic z.external(...) that accepts any object that conforms to a particular interface, probably this:

interface Schema<T> {
  parse: (data:unknown): T;
  check: (data:unknown): data is T;
}

You'd have to define a class that defines these methods and delegates to the appropriate methods on your third-party schemas. If you define a generic class, you should be able to get type inference to work as well (assuming the third party library has some type inference support).

What libraries are you trying to integrate with?

@cdaringe
Copy link
Author

ATM im extending my schema with @types/puppeteer::Viewport. i have something like { url: string, viewport: Viewport } 🤔

@colinhacks
Copy link
Owner

Ah so you're only interested in incorporating static types in your schemas, not doing runtime validation, correct?

You should just construct your own types using TypeScript's functionality:

const BaseType = z.object({ url: z.string() });
type BaseType = z.infer<typeof Test>;

type FinalType = BaseType & { viewport: Viewport };
 => { url: string; viewport: Viewport }

@colinhacks
Copy link
Owner

colinhacks commented May 18, 2020

@cdaringe Just thought of a better way to do this!

const Viewport: z.ZodType<Viewport> = z.any();

const FullSchema = z.object({ url: z.string(), viewport: Viewport });

This way you can still do validations with parse as you'd expect since z.any() allows any inputs, and the type inference works as expected. 👍

@cdaringe
Copy link
Author

Doh! I figured I was missing something! Perfecto, thx!

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

2 participants