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>);
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too