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

support for Maybe<T> special case #91

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Commits on Jul 26, 2022

  1. support for Maybe<T> special case

    - we can configure if Maybe represents nullable, optional, or both.
    - we can define which generic types to use as Maybe (e.g. Maybe, InputMaybe, etc). Can be multiple.
    - when ts-to-zod encounters a generic type in the list of "Maybe"s, it skips the schema generation for them.
    - when it encounters them as being used, it makes a call to `maybe()` function.
    - the `maybe` function is defined depending on the nullable/optional config.
    
    This is useful to work in conjunction with other codegen tools, like graphql codegens.
    
    e.g.
    
    ```ts
    // config
    /**
     * ts-to-zod configuration.
     *
     * @type {import("./src/config").TsToZodConfig}
     */
    module.exports = [
      {
        name: "example",
        input: "example/heros.ts",
        output: "example/heros.zod.ts",
        maybeTypeNames: ["Maybe"],
      }
    ];
    
    // input
    
    export type Maybe<T> = T | null | "whatever really"; // this is actually ignored
    
    export interface Superman {
      age: number;
      aliases: Maybe<string[]>;
    }
    
    // output
    
    export const maybe = <T extends z.ZodTypeAny>(schema: T) => {
      return schema.nullable();
    };
    
    export const supermanSchema = z.object({
        age: z.number(),
        alias: maybe(z.array(z.string()))
    });
    ```
    
    Configuration:
    
    By default, this feature is turned off. When adding the list of type names to be considered 'Maybe's, we turn it on.
    Maybe is nullable and optional by default, unless specified otherwise.
    
    We can set this in CLI options...
    
    - `maybeOptional`: boolean, defaults to true
    - `maybeNullable`: boolean, defaults to true
    - `maybeTypeName`: string, multiple. List of type names.
    
    …as well as in the ts-to-zod config file.
    - `maybeOptional`: boolean
    - `maybeNullable`: boolean
    - `maybeTypeNames`: string[]. list of type names.
    eturino committed Jul 26, 2022
    Configuration menu
    Copy the full SHA
    65eb6c5 View commit details
    Browse the repository at this point in the history
  2. typo

    eturino committed Jul 26, 2022
    Configuration menu
    Copy the full SHA
    eb8a0ab View commit details
    Browse the repository at this point in the history