首页 > 解决方案 > 在Javascript文件中,如何在tsdoc/jsdoc中注释重载函数签名(可以被vscode智能识别)

问题描述

我有这些定义:

class Entity {}
class Point {}
class Edge {}
class A {
  from(x, y) {
    if (x == null) {
      return this.remember('_from')
    } else if (x instanceof Entity || x instanceof Point) {
      this.remember('_from', new Edge(x))
      return this
    } else {
      this.remember('_from', new Edge(new Point(x, y)))
      return this
    }
  }
}

from方法具有多个签名,如上所示。我想为 vscode 智能感知写 jsdoc 评论。

我有两种方法,但它们都不起作用:


class A {
  /**
   * @type {((x: number, y: number) => this) & ((x: Entity|Point) => this) & (() => Edge)}
   */
  from(x, y) {
    if (x == null) {
      return this.remember('_from')
    } else if (x instanceof Entity || x instanceof Point) {
      this.remember('_from', new Edge(x))
      return this
    } else {
      this.remember('_from', new Edge(new Point(x, y)))
      return this
    }
  }
}


class A {
  /**
   * @template T
   * @typedef {{
   *  (this: T, x: number, y: number): T;
   *  (this: T, entity: Entity): T;
   *  (this: T, point: Point): T;
   *  (): Edge;
   * }} fromType
   *
   * @type {fromType<this>}
   */
  from(x, y) {
    if (x == null) {
      return this.remember('_from')
    } else if (x instanceof Entity || x instanceof Point) {
      this.remember('_from', new Edge(x))
      return this
    } else {
      this.remember('_from', new Edge(new Point(x, y)))
      return this
    }
  }
}

我现在有一个工作区,但它不是重载,因为参数 x 不能以确切的类型提示。


class A {
  /**
   * @template {unknown} T
   * @param {T} [x]
   * @param {number} [y]
   * @returns {T extends Entity|Point|number ? this : Edge}
   */
  from(x, y) {
    if (x == null) {
      return this.remember('_from')
    } else if (x instanceof Entity || x instanceof Point) {
      this.remember('_from', new Edge(x))
      return this
    } else {
      this.remember('_from', new Edge(new Point(x, y)))
      return this
    }
  }
}

那么有没有办法在 tsdoc 中编写正确的函数签名重载以及如何编写它?谢谢你。

标签: javascripttypescriptintellisensetsdoc

解决方案


推荐阅读