如何为仅返回特定值的JavaScript函数编写规范文档?
规范指定JSDoc返回值的方法
你这个思路完全没问题!现在主流的JSDoc规范确实支持用字符串字面量联合类型来更精确地指定返回值,比原来只写{string}加描述要规范得多,而且编辑器(比如VS Code)和静态检查工具(如ESLint、TypeScript的checkJS模式)都能更好地识别,还能给开发者提供准确的代码提示。
直接指定联合类型的写法
最简洁的方式就是直接在@return的类型里列出所有可能的字符串字面量:
/** * Returns the current post status. * @return {'inactive'|'active'|'blocked'} The current post status, limited to three explicit string values. */ function getStatus() { if (this.status === 0) return 'inactive'; if (this.status === 1) return 'active'; if (this.status === 2) return 'blocked'; }
这种写法不需要额外的类型定义,适合单个函数使用的场景,语法简洁清晰,完全符合JSDoc的规范。
复用类型的写法(适合多场景使用)
如果这个状态类型会在多个函数或地方用到,推荐用@typedef先定义一个可复用的类型,再在返回值里引用:
/** * @typedef {'inactive'|'active'|'blocked'} PostStatus * @description Possible status values for a post. */ /** * Returns the current post status. * @return {PostStatus} The current status of the post. */ function getStatus() { if (this.status === 0) return 'inactive'; if (this.status === 1) return 'active'; if (this.status === 2) return 'blocked'; }
这种写法的好处是可以统一维护状态值,避免重复编写,也让代码的可读性更强。
关于你提到的写法
你之前设想的@return {string=('inactive'|'active'|'blocked')}其实方向是对的,但正确的语法不需要string=,因为'inactive'、'active'、'blocked'本身就是字符串类型的字面量,它们的联合类型自然属于string的子类型,直接写{'inactive'|'active'|'blocked'}就足够准确了。
内容的提问来源于stack exchange,提问作者CryptoBird
相关产品推荐
相关产品推荐

