MCPcopy Index your code
hub / github.com/microsoft/TypeChat / getZodSchemaAsTypeScript

Function getZodSchemaAsTypeScript

typescript/src/zod/validate.ts:80–266  ·  view source on GitHub ↗
(schema: Record<string, z.ZodType>)

Source from the content-addressed store, hash-verified

78 * @returns The TypeScript source code corresponding to the schema.
79 */
80export function getZodSchemaAsTypeScript(schema: Record<string, z.ZodType>): string {
81 let result = "";
82 let startOfLine = true;
83 let indent = 0;
84 const entries = Array.from(Object.entries(schema));
85 let namedTypes = new Map<object, string>(entries.map(([name, type]) => [getTypeIdentity(type), name]));
86 for (const [name, type] of entries) {
87 if (result) {
88 appendNewLine();
89 }
90 const description = type.description;
91 if (description) {
92 for (const comment of description.split("\n")) {
93 append(`// ${comment}`);
94 appendNewLine();
95 }
96 }
97 if (getTypeKind(type) === "object") {
98 append(`interface ${name} `);
99 appendObjectType(type as z.ZodObject);
100 }
101 else {
102 append(`type ${name} = `);
103 appendTypeDefinition(type);
104 append(";");
105 }
106 appendNewLine();
107 }
108 return result;
109
110 function append(s: string) {
111 if (startOfLine) {
112 result += " ".repeat(indent);
113 startOfLine = false;
114 }
115 result += s;
116 }
117
118 function appendNewLine() {
119 append("\n");
120 startOfLine = true;
121 }
122
123 function appendType(type: z.ZodType, minPrecedence = 0) {
124 const name = namedTypes.get(getTypeIdentity(type));
125 if (name) {
126 append(name);
127 }
128 else {
129 const parenthesize = getTypePrecedence(type) < minPrecedence;
130 if (parenthesize) append("(");
131 appendTypeDefinition(type);
132 if (parenthesize) append(")");
133 }
134 }
135
136 function appendTypeDefinition(type: z.ZodType) {
137 switch (getTypeKind(type)) {

Callers 3

schemaOfFunction · 0.85
zod.test.tsFile · 0.85
createZodJsonValidatorFunction · 0.85

Calls 6

getTypeIdentityFunction · 0.85
appendNewLineFunction · 0.85
appendFunction · 0.85
getTypeKindFunction · 0.85
appendObjectTypeFunction · 0.85
appendTypeDefinitionFunction · 0.85

Tested by 1

schemaOfFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…