admin管理员组

文章数量:1328037

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; // autopletions 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.

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; // autopletions 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.

Share Improve this question asked May 29, 2023 at 1:13 bristwebbristweb 1,22517 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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; // autopletions and vscode linting should work here
 // do stuff
}

This works:

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

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

One thing you could try is to take advantage of the separation between the type namespace and the values namespace by exporting the type of the schema with the same name as the schema. For example you could say

export const personSchema = z.object({ /* ... */ });
// If you're using eslint, it may plain here but you can ignore
// the redeclaration plaint
export type personSchema = z.infer<typeof personSchema>;

When Typescript is working out the types from the JSDOC the personSchema type will be imported and will resolve so you get the correct value with:

/**
 * @param {personSchema} person
 */
function (person) {
  person.name;
};

This will work with regular JS since the types won't exist so only the schema will be imported, and it will also work with TS because it can distinguish between something being used as a type and something that is a value.

本文标签: javascriptHow to infer Zod type in JSDoc (without TypeScript)Stack Overflow