原文地址:Types in JavaScript With Zod and JSDoc
在 js 文件中使用注释定义类型,并且在其他文件中引用。
// file: file-1.js
/**
* @typedef Candy
* @property {string} name
* @property {"chocolate"|"gummy"} type
*/
// 注意,file-1.js 要是个 module,所以必须有 export
export {}
// file: file-2.js
/** @type { import('./file-1').Candy[] } */
const candy = [
{ name: "Kit Kat", type: "chocolate" },
{ name: "Peach Rings", type: "gummy" },
];
在 VSCode 中将自动提示:
在文件顶部添加
@ts-check后,将会有类型检查: