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

Optional is not working in nested schema #58

Open
menocomp opened this issue Jul 9, 2020 · 0 comments
Open

Optional is not working in nested schema #58

menocomp opened this issue Jul 9, 2020 · 0 comments

Comments

@menocomp
Copy link

menocomp commented Jul 9, 2020

First time to use this library and I like it :)
However I have an issue with optional strings:

The inferred string type is not marked as optional when schema is nested:

const PhoneSchema = createSchema(
  {
    req: Type.number({ required: true }),
    opt: Type.string(), // => I am setting 'opt' as optional
  },
  { _id: false, versionKey: false },
);

const UserSchema = createSchema(
  {
    req: Type.string({ required: true }),
    opt: Type.string(), // => I am setting 'opt' as optional
    phones: Type.array({ required: true }).of(PhoneSchema),
  },
  { _id: false, versionKey: false },
);

export type UserProps = ExtractProps<typeof UserSchema>;

Hover over UserProps I see this:

type UserProps = {
    req: string;
    phones: {
        req: number;
        opt: string;// 'opt' is not optional!
    }[];
    opt?: string; // 'opt' here is optional which is correct
}

I can only fix this by using of function on the object not in the schema as follows:

const phoneDefinition = {
  req: Type.number({ required: true }),
  opt: Type.string(),
};

const PhoneSchema = createSchema(phoneDefinition, {
  _id: false,
  versionKey: false,
});

const UserSchema = createSchema(
  {
    req: Type.string({ required: true }),
    opt: Type.string(),
    phones: Type.array({ required: true }).of(phoneDefinition),
  },
  { _id: false, versionKey: false },
);

Now I see correct optional fields as follows:

type UserProps = {
    req: string;
    phones: {
        req: number;
        opt?: string; =>  this is correct now
    }[];
    opt?: string;
}

Am I using this library correctly?
Is this a bug?

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

1 participant