Skip to content

Commit

Permalink
fix(console): fix the zod-to-ts type infer bug (#5566)
Browse files Browse the repository at this point in the history
fix the zod-to-ts type infer bug
  • Loading branch information
simeng-li authored Mar 28, 2024
1 parent d1b1985 commit 6990a3e
Showing 1 changed file with 14 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import fs from 'node:fs';

import {
jwtCustomizerUserContextGuard,
accessTokenPayloadGuard,
clientCredentialsPayloadGuard,
jwtCustomizerUserContextGuard,
} from '@logto/schemas';
import prettier from 'prettier';
import { type ZodTypeAny } from 'zod';
import { zodToTs, printNode } from 'zod-to-ts';
import { printNode, zodToTs } from 'zod-to-ts';

const filePath = 'src/consts/jwt-customizer-type-definition.ts';

Expand All @@ -19,7 +19,18 @@ const typeIdentifiers = `export enum JwtCustomizerTypeDefinitionKey {
};`;

const inferTsDefinitionFromZod = (zodSchema: ZodTypeAny, identifier: string): string => {
const { node } = zodToTs(zodSchema, identifier);
/**
* We have z.lazy() used for defining Json objects in the zod schemas.
* @see https://zod.dev/?id=json-type
* zod-to-ts does not support z.lazy() yet. It will use the root type of the lazy schema. Which will be the identifier we pass to the function.
* @see https://github.com/sachinraja/zod-to-ts?tab=readme-ov-file#zlazy
*
* The second argument is the root type identifier for the schema.
* Here we use 'Record<string, unknown>' as the root type identifier. So all the Json objects will be inferred as Record<string, unknown>.
* This is a limitation of zod-to-ts. We can't infer the exact type of the Json objects.
* This solution is hacky but it works for now. The impact is it will always define the type identifer as Record<string, unknown>.
*/
const { node } = zodToTs(zodSchema, 'Record<string, unknown>', { nativeEnums: 'union' });
const typeDefinition = printNode(node);

return `type ${identifier} = ${typeDefinition};`;
Expand Down

0 comments on commit 6990a3e

Please sign in to comment.