JSDoc重载函数在TypeScript中失效,如何实现同等类型标注?
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
@overloadentry 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
overloaded2TypeScript 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

