无法用JSDoc为泛型恒等函数添加类型注解
问题分析与解决
你遇到的问题在于变量级泛型和函数调用泛型的混淆。你给id变量标注的@template A是属于变量本身的泛型参数,而非函数调用时可以动态推断的泛型。TypeScript无法在调用id(5)时自动将这个变量级的A推断为number,因为它会被视为一个未指定的、可能是任意类型的参数,因此出现类型不匹配的错误。
解决方案1:直接给函数标注泛型(推荐)
去掉变量上的泛型标注,直接给函数本身添加泛型注释,让TypeScript在调用时自动推断类型:
// @ts-check /** * @template A * @param {A} a * @returns {A} */ const id = (a) => a /** * @type {number} */ export const five = id(5); // 正常运行
解决方案2:调整类型标注为函数泛型
如果你希望保留Identity回调类型,可以将变量的类型标注为泛型函数类型,而非绑定一个未指定的泛型参数:
// @ts-check /** * @template A * @callback Identity * @param {A} a * @returns {A} */ /** * @type {<A>(a: A) => A} */ const id = (a) => a /** * @type {number} */ export const five = id(5); // 正常运行
解决方案3:显式指定泛型调用
也可以在调用id时显式指定泛型参数,强制A为number:
// @ts-check /** * @template A * @callback Identity * @param {A} a * @returns {A} */ /** * @template A * @type {Identity<A>} */ const id = (a) => a /** * @type {number} */ export const five = id<number>(5); // 正常运行
内容的提问来源于stack exchange,提问作者Jordan Mackie
相关产品推荐
相关产品推荐

