[英]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
有幾種解決方案:
/**
* 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) {
...
}
function getRead(/**@type {number}*/index, /**@type {string}*/user) {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.