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

Add IsNullable and IsOptional #900

Open
jinyongp opened this issue Jun 27, 2024 · 0 comments
Open

Add IsNullable and IsOptional #900

jinyongp opened this issue Jun 27, 2024 · 0 comments

Comments

@jinyongp
Copy link

jinyongp commented Jun 27, 2024

I'd like to add IsNullable and IsOptional types to check if they contain null and undefined, respectively.

type IsNullable<T> = Extract<T, null> extends never ? false : true
type IsOptional<T> = Extract<T, undefined> extends never ? false : true
type T1 = IsNullable<string> // false
type T2 = IsNullable<string | null> // true
type T3 = IsNullable<string | undefined> // false
type T4 = IsNullable<string | null | undefined> // true

type T5 = IsOptional<string> // false
type T6 = IsOptional<string | null> // false
type T7 = IsOptional<string | undefined> // true
type T8 = IsOptional<string | null | undefined> // true

I'm currently using these types to generate a Zod schema based on an interface. They help choose the appropriate type depending on whether a value can be null or undefined.

type Zodify<T extends Record<string, any>> = {
  [K in keyof T]-?: IsNullable<T[K]> extends true
    ? z.ZodNullable<z.ZodType<T[K]>>
    : IsOptional<T[K]> extends true
      ? z.ZodOptional<z.ZodType<T[K]>>
      : z.ZodType<T[K]>
};

interface Foo {
  bar: string;
  nullable: number | null;
  optional?: string;
  optionalNullable?: string | null;
}

const schema = z.object({
  bar: z.string(),
  nullable: z.number().nullable(),
  optional: z.string().optional(),
  optionalNullable: z.string().optional().nullable(), // should chain optional first
} satisfies Zodify<Foo>);

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants