【问题标题】:JSDoc: Trying to use @typedef with a generic @callbackJSDoc:尝试将@typedef 与通用@callback 一起使用
【发布时间】:2023-02-08 07:41:11
【问题描述】:

我对 JSDoc 有点陌生,但我正在尝试定义一个具有通用类型函数的 typedef(返回类型是从参数类型推断的)。

看起来下面的代码应该导致 bar 常量的类型为 string。相反,我得到一个 any 类型。

/**
 * @template T
 * @callback MyFunction
 * @param {T} val
 * @return {T}
 */

/**
 * @typedef MyType
 * @property {MyFunction} myFunction
 */

/** @type {MyType} */
const foo = {};
const bar = foo.myFunction('a string');

【问题讨论】:

    标签: javascript generics typedef jsdoc


    【解决方案1】:

    在您的情况下,您应该为 myFunction 属性指定通用类型:

    /**
     * @typedef MyType
     * @property {MyFunction<string>} myFunction
     */
    

    或者你也可以将MyType设为通用

    /**
     * @template T
     * @typedef MyType
     * @property {MyFunction<T>} myFunction
     */
    

    但是你应该在为 foo 定义类型时指定泛型类型:

    /** @type {MyType<string>} */
    const foo = {};
    const bar = foo.myFunction('a string');
    
    // OR
    /** @type {MyType<string|number>} */
    const foo = {};
    const bar = foo.myFunction('a string');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-08
      • 2016-03-25
      • 2013-12-25
      • 2014-09-01
      • 1970-01-01
      相关资源
      最近更新 更多