【问题标题】:JSdoc how to tell that a function returns the same type as a parameterJSdoc 如何判断函数返回与参数相同的类型
【发布时间】:2019-04-14 14:19:11
【问题描述】:

你会用 C# 编写

T RandomFrom< T >( List< T > list ) {
    return list[ ( int ) Math.Floor( new Random().Next() * list.Count ) ];
}

在编写 JS 函数时我应该如何做同样的事情? 我试过了:

/**
 * @type {*} T
 * @param {T[]} list
 * @returns {T} 
 */
function randomFrom ( list ) {
    return list[ Math.floor( Math.random() * list.length ) ];
}

但是 VS Code 告诉我 randomFrom(list: any[]): any,我希望它类似于 randomFrom(list: &lt;T&gt;[]): &lt;T&gt;。我该如何做到这一点?将 T 放入 &lt;&gt; 使其成为箭头函数。

【问题讨论】:

标签: jsdoc


【解决方案1】:

这行得通:

/**
 * @template T
 * @param {T} a
 * @returns {T}
 */
function (a){
  return a
}

查看更多:https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#template

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 2019-12-23
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多