Skip to content

Commit

Permalink
fix: Fix nullable (#92)
Browse files Browse the repository at this point in the history
* Fix array or null

Closed #86

* Fix other nullable cases
  • Loading branch information
fabien0102 committed Aug 26, 2022
1 parent c5abe8c commit f2321a3
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/core/generateZodSchema.test.ts
Expand Up @@ -831,6 +831,56 @@ describe("generateZodSchema", () => {
`);
});

it("should deal with array of null or null", () => {
const source = `export type Example = {
field?: Array<string | null> | null
}`;

expect(generate(source)).toMatchInlineSnapshot(`
"export const exampleSchema = z.object({
field: z.array(z.string().nullable()).optional().nullable()
});"
`);
});

it("should deal with partial or null", () => {
const source = `export type Example = {
field: Partial<{foo: string}> | null
}`;

expect(generate(source)).toMatchInlineSnapshot(`
"export const exampleSchema = z.object({
field: z.object({
foo: z.string()
}).nullable().partial()
});"
`);
});

it("should deal with ReadonlyArray or null", () => {
const source = `export type Example = {
field: ReadonlyArray<"foo" | "bar"> | null
}`;

expect(generate(source)).toMatchInlineSnapshot(`
"export const exampleSchema = z.object({
field: z.array(z.union([z.literal(\\"foo\\"), z.literal(\\"bar\\")])).nullable()
});"
`);
});

it("should deal with Record or null", () => {
const source = `export type Example = {
field: Record<string, string> | null
}`;

expect(generate(source)).toMatchInlineSnapshot(`
"export const exampleSchema = z.object({
field: z.record(z.string()).nullable()
});"
`);
});

it("should allow nullable on union properties", () => {
const source = `export interface A {
a: number | string | null;
Expand Down
4 changes: 4 additions & 0 deletions src/core/generateZodSchema.ts
Expand Up @@ -256,6 +256,7 @@ function buildZodPrimitive({
z,
typeNode: f.createArrayTypeNode(typeNode.typeArguments[0]),
isOptional,
isNullable,
jsDocTags: {},
sourceFile,
dependencies,
Expand All @@ -270,6 +271,7 @@ function buildZodPrimitive({
z,
typeNode: typeNode.typeArguments[0],
isOptional,
isNullable,
jsDocTags,
sourceFile,
isPartial: true,
Expand All @@ -285,6 +287,7 @@ function buildZodPrimitive({
z,
typeNode: typeNode.typeArguments[0],
isOptional,
isNullable,
jsDocTags,
sourceFile,
isRequired: true,
Expand All @@ -300,6 +303,7 @@ function buildZodPrimitive({
z,
typeNode: typeNode.typeArguments[0],
isOptional,
isNullable,
jsDocTags,
sourceFile,
dependencies,
Expand Down

0 comments on commit f2321a3

Please sign in to comment.