From 0fee6095405ef8e06ce70500fd6d1317b2de1e17 Mon Sep 17 00:00:00 2001 From: Sachin Raja Date: Fri, 7 Apr 2023 09:30:27 -0700 Subject: [PATCH] move getType to _def.getType --- src/index.ts | 2 +- src/types.ts | 2 +- src/utils.ts | 2 +- test/describe.test.ts | 28 ++++++++++++++++++++++++++++ test/example2.ts | 20 ++++++++++++++++++++ 5 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 test/describe.test.ts create mode 100644 test/example2.ts diff --git a/src/index.ts b/src/index.ts index 5a03c31..343c1ab 100644 --- a/src/index.ts +++ b/src/index.ts @@ -27,7 +27,7 @@ const callGetType = ( let type: ReturnType | undefined // this must be called before accessing 'type' - if (zod.getType) type = zod.getType(ts, identifier, options) + if (zod._def.getType) type = zod._def.getType(ts, identifier, options) return type } diff --git a/src/types.ts b/src/types.ts index b837317..82b5d13 100644 --- a/src/types.ts +++ b/src/types.ts @@ -23,4 +23,4 @@ export type GetTypeFunction = ( options: RequiredZodToTsOptions, ) => ts.Identifier | ts.TypeNode -export type GetType = { getType?: GetTypeFunction } +export type GetType = { _def: { getType?: GetTypeFunction } } diff --git a/src/utils.ts b/src/utils.ts index f2c883e..1b3a163 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -38,7 +38,7 @@ export const printNode = (node: ts.Node, printerOptions?: ts.PrinterOptions) => } export const withGetType = (schema: T, getType: GetTypeFunction): T => { - schema.getType = getType + schema._def.getType = getType return schema } diff --git a/test/describe.test.ts b/test/describe.test.ts new file mode 100644 index 0000000..7d82f3c --- /dev/null +++ b/test/describe.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest' +import { z } from 'zod' +import { withGetType, zodToTs } from '../src' +import { printNodeTest } from './utils' + +describe('z.describe()', () => { + it('supports describing schema after withGetType', () => { + const Enum = z.nativeEnum({ + ONE: 1, + TWO: 2, + }) + + withGetType(Enum, ts => ts.factory.createIdentifier('Enum')) + + const schema = z.object({ + key: Enum.describe('Comment for key'), + }) + + const { node } = zodToTs(schema) + + expect(printNodeTest(node)).toMatchInlineSnapshot(` + "{ + /** Comment for key */ + key: Enum; + }" + `) + }) +}) diff --git a/test/example2.ts b/test/example2.ts new file mode 100644 index 0000000..a307aae --- /dev/null +++ b/test/example2.ts @@ -0,0 +1,20 @@ +import { z } from 'zod' +import { printNode, withGetType, zodToTs } from '../src' + +const Enum = z.nativeEnum({ + ONE: 1, + TWO: 2, +}) + +withGetType(Enum, ts => ts.factory.createIdentifier('Enum')) + +const schema = z.object({ + key: Enum.describe('Comment for key'), +}) + +const { node } = zodToTs(schema, undefined, { resolveNativeEnums: true }) +console.log(printNode(node)) +// { +// /** Comment for key */ +// key: unknown; +// }