davidmdm / myzod

MIT License
315 stars 20 forks source link

Propose that OptionalType schema not be private #21

Closed kaedub closed 4 years ago

kaedub commented 4 years ago

Overview

I want to start by saying thanks and that myzod has been my favorite JS validation library since finding it and I would like to contribute something if possible.

My proposal is that the schema property on OptionalType, NullableType, ArrayType have private removed.

Problem

Consider the following schema:

const s = myzod.object({
  name: myzod.string(),
  age: myzod.number().optional(),
  eyeColor: myzod.enum(SomeEnum).optional(),
});

I would like to be able to do type checking on the schema so that I may filter fields by type. However, I can't access nested types without a Typescript error.

const enumFields = Object.entries(s.shape())
    .filter((f) => {
      return (
        f[1] instanceof EnumType ||
        (f[1] instanceof OptionalType
        && f[1].schema instanceof EnumType)
        // Property 'schema' is private and only accessible within class 'OptionalType<T>'
      )
    })
    .map((f) => f[0]);

Suggested Solution

export declare class OptionalType<T extends AnyType> extends Type<Infer<T> | undefined> {
-   private readonly schema;
+   readonly schema;
    constructor(schema: T);
    parse(value: unknown, opts?: any): Infer<T> | undefined;
    and<K extends AnyType>(schema: K): IntersectionType<this, K>;
}

Unless there is a reason for this being private, I'd like to make a PR for this.

Thanks!

davidmdm commented 4 years ago

Hey. I see no reason for it remain private. At first I thought of myzod as very simple and tried to keep meta programming of internal schemas out of it, but if the community wants it, then I think that is fine.

If you make a PR for this and the tests pass, I will merge and make a release. Thanks for your efforts !

davidmdm commented 4 years ago

merged.

davidmdm commented 4 years ago

This has been merged but I am just waiting on your EnumType Coercion PR to make a release :) @kaedub