Skip to content

Commit

Permalink
move getType to _def.getType
Browse files Browse the repository at this point in the history
  • Loading branch information
sachinraja committed Apr 7, 2023
1 parent 1d15088 commit 0fee609
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const callGetType = (
let type: ReturnType<GetTypeFunction> | 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
}

Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ export type GetTypeFunction = (
options: RequiredZodToTsOptions,
) => ts.Identifier | ts.TypeNode

export type GetType = { getType?: GetTypeFunction }
export type GetType = { _def: { getType?: GetTypeFunction } }
2 changes: 1 addition & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export const printNode = (node: ts.Node, printerOptions?: ts.PrinterOptions) =>
}

export const withGetType = <T extends ZodTypeAny & GetType>(schema: T, getType: GetTypeFunction): T => {
schema.getType = getType
schema._def.getType = getType
return schema
}

Expand Down
28 changes: 28 additions & 0 deletions test/describe.test.ts
Original file line number Diff line number Diff line change
@@ -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;
}"
`)
})
})
20 changes: 20 additions & 0 deletions test/example2.ts
Original file line number Diff line number Diff line change
@@ -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;
// }

0 comments on commit 0fee609

Please sign in to comment.