Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to infer Zod type in JSDoc (without TypeScript)

Suppose I have the schema in javascript:

import {z} from "zod";
let personSchema = z.object({
  name: z.string(),
  id: z.number()
});

now I want to use the type somewhere else:

/** 
* @param {{name:string, id:number}} person 
* but should instead be something like this?:
* @param {???(typeof z)["infer"]<typeof personSchema>???} person 
*/
function (person) {
 person.name; // autocompletions and vscode linting should work here
 // do stuff
}

Of course this would be easy in typescript, but I'm trying to use JSDOC since the project doesn't allow TypeScript.

like image 261
bristweb Avatar asked Sep 16 '25 12:09

bristweb


2 Answers

Here's a way to use z.infer to define a type using jsdoc (similar to the way you would do so in Typescript), then use the new type in the function annotation:

import {z} from "zod";

/** 
* @typedef {z.infer<typeof PersonSchema>} Person
*/ 
let PersonSchema = z.object({
  name: z.string(),
  id: z.number()
});

/** 
* @param {Person} person
*/ 
function (person) {
 person.name; // autocompletions and vscode linting should work here
 // do stuff
}
like image 196
Duane J Avatar answered Sep 19 '25 02:09

Duane J


This works:

/** 
* @param {ReturnType<(typeof personSchema)["parse"]>} person
*/ 
function (person) {
 person.name; // autocompletions and vscode linting should work here
 // do stuff
}

Although this works, I suspect there is a better solution.

like image 28
bristweb Avatar answered Sep 19 '25 02:09

bristweb