【问题标题】:Weird typescript inference with explicit JSDoc annotations带有显式 JSDoc 注释的奇怪打字稿推断
【发布时间】:2021-07-28 16:29:43
【问题描述】:

我用 typescript 样式的 JSDoc 注释编写了 vanilla JS。

推断的返回类型是Promise<new (width?: number, height?: number) => HTMLImageElement>,我错过了什么吗?

/**
 * Load an image from a given URL
 * @param {String} url The URL of the image resource
 * @returns {Promise<Image>}
 */
export function loadImage(url) {
  /*
   * We are going to return a Promise which, when we .then
   * will give us an Image that should be fully loaded
   */
  return new Promise((resolve) => {
    /*
     * Create the image that we are going to use to
     * to hold the resource
     */
    const image = new Image();
    /*
     * The Image API deals in even listeners and callbacks
     * we attach a listener for the "load" event which fires
     * when the Image has finished the network request and
     * populated the Image with data
     */
    image.addEventListener("load", () => {
      /*
       * You have to manually tell the Promise that you are
       * done dealing with asynchronous stuff and you are ready
       * for it to give anything that attached a callback
       * through .then a realized value.  We do that by calling
       * resolve and passing it the realized value
       */
      // @ts-ignore
      resolve(image);
    });
    /*
     * Setting the Image.src is what starts the networking process
     * to populate an image.  After you set it, the browser fires
     * a request to get the resource.  We attached a load listener
     * which will be called once the request finishes and we have
     * image data
     */
    image.src = url;
  });
}

【问题讨论】:

    标签: javascript typescript jsdoc


    【解决方案1】:

    您使用了错误的返回类型:@returns {Promise&lt;Image&gt;}

    Image 不能单独用作类型。

    看看Image TS 内置类型中的声明:

    declare var Image: {
        new(width?: number, height?: number): HTMLImageElement;
    };
    

    尽管Imageconstructor - 它没有被声明为一个类。因此,您不能在类型范围内使用它。

    使用Promise&lt;Image&gt;与本例相同:

    const x = 10;
    
    type Y = x;
    

    x 是一个值,而Y 是一个类型。你不能混合它们。 您只能在类型范围内使用 classesenums

    您可能已经注意到,Image 是一个返回 HTMLImageElement 的构造函数。这种类型应该在你的 JSDOC 中使用。

    所以,你有两个选择:

    1. @returns {Promise&lt;InstanceType&lt;Image&gt;&gt;}
    2. @returns {Promise&lt;HTMLImageElement&gt;}

    将鼠标悬停在const image 上,您会看到它是HTMLImageElement

    请记住,您可以在 jsdoc 中使用 typescript utility types

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 2022-06-20
      • 2017-05-20
      相关资源
      最近更新 更多