繁体   English   中英

JSDoc function 返回一个自身的参数

[英]JSDoc function returning a parameter of itself

我需要记录一个 function 有条件地返回其参数之一。 但是 JSDoc 似乎不接受变量作为返回值。

我试图在返回类型{1 | 0}之后做这样的事情 {1 | 0}逻辑

/**
 * Finds the page with given index and returns
 *  - index if it does not exist
 *  - user if user doesn't have permissions to read
 *  - else the page itself 
 * 
 * @param {number} index 
 * @param {string} user 
 * @returns {index|user|Page}
 */
function getRead(index, user) {
    let page = pages.find(page => page.details.index == index);
    if (page && page.canRead(user)) {
        return page;
    } else if (!page) return index;
    else return user;
}

但它无法识别并且返回值只是any值,如果我使用{string|number|Page}作为类型,之后在我的代码中我会做这样的事情

if(page == index) return res.send(`Page ${index} does not exist`);
if(page == user) return res.send(`No permissions to view page ${index}`);
//page still recognized as number | string | Page
//no code completion or property suggestions on page

我还尝试添加类型检查以到达那里,但我不想相信像这样懒惰的解决方案是唯一的解决方案,必须有更好的方法来处理这个问题

if(typeof page == "number" || page == index) return res.send(`Page ${index} does not exist`);
if(typeof page == "string" || page == user) return res.send(`No permissions to view page ${index}`);
//page recognized as Page

有几种解决方案:

  1. 对参数使用通用类型
/**
 * Finds the page with given index and returns
 *  - index if it does not exist
 *  - user if user doesn't have permissions to read
 *  - else the page itself 
 * 
 * @template {number} IndexType
 * @template {string} UserType
 * @param {IndexType} index 
 * @param {UserType} user 
 * @returns {IndexType|UserType|Page}
 */
function getRead(index, user) {
 ...
}

在此处输入图像描述

  1. 完全删除 function 的 JSDoc 并依赖 TypeScript 的类型推断
function getRead(/**@type {number}*/index, /**@type {string}*/user) {
  ...
}

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM