You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSDoc重载函数在TypeScript中失效,如何实现同等类型标注?

Can TypeScript's JSDoc support match TypeScript's type annotation level for overloaded functions?

Absolutely! TypeScript's JSDoc support does let you replicate the exact same overload behavior as native TypeScript code—you just need to use the right syntax for documenting multiple signatures.

The Issue With Your Original JSDoc Code

Your initial approach used two separate JSDoc comment blocks above the function. TypeScript's language service only processes the first comment block and ignores the second, which is why only the string overload was being recognized.

Correct JSDoc Overload Syntax

To properly document multiple overloads, wrap all distinct signatures in a single comment sequence using the @overload tag for each one. Here's the fixed version of your function:

/**
 * @overload
 * @param {string} param
 * @returns {'string result'}
 */
/**
 * @overload
 * @param {number} param
 * @returns {'number result'}
 */
/**
 * @param {string | number} param
 * @returns {'string result' | 'number result'}
 */
function overloaded(param) {
  switch (typeof param) {
    case 'string':
      return 'string result';
    case 'number':
      return 'number result';
  }
  throw new Error(`Invalid type: ${typeof param}`);
}

// Now VS Code will correctly infer return types:
overloaded('seven'); // Returns 'string result'
overloaded(7);       // Returns 'number result'
// overloaded(true);  // Type error (correctly caught!)

How This Works

  • Each @overload entry defines a unique function signature, just like in native TypeScript.
  • The final JSDoc block (without @overload) documents the implementation's underlying type (the union that covers all overload cases).
  • TypeScript's language service will now recognize all overloads, providing accurate autocompletion and type checking that matches the behavior of your overloaded2 TypeScript function perfectly.

Equivalence to Native TypeScript

This JSDoc setup is fully interchangeable with your TypeScript implementation. Both enforce the same constraints:

  • Passing a string returns the literal type 'string result'
  • Passing a number returns the literal type 'number result'
  • Passing any other type triggers a type error

内容的提问来源于stack exchange,提问作者Tomáš Hübelbauer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:03:34