如何在 typescript jsdoc 中引用私有类字段

问题描述 投票:0回答:2

请告诉我:如何在 typescript jsdoc 中引用私有类字段?

脚本.js:

// @ts-check

class C {

    /** @type { null | string | number } */
    #x = null;

    // /** @type { ( x : C[ 'x' ] ) => void } */
    // /** @type { ( x : this[ 'x' ] ) => void } */
    // /** @type { ( x : this[ '#x' ] ) => void } */
    // /** @type { ( x : this[ #x ] ) => void } */
    // /** @type { ( x : this#x ) => void } */
    // /** @type { ( x : this.#x ) => void } */
    // /** @type { ( x : this[ #'x' ] ) => void } */
    f( x ) { };

};
javascript typescript jsdoc hidden-field
2个回答
0
投票

这是 Typescript 本身的一个悬而未决的问题。但有一个解决方法可以得到你想要的东西。

class C {
  #x: null | string | number = null;

  f = (() => {
    const privX = this.#x
    return (x: typeof privX) => {
    }
  })();
};

0
投票

一种可能的解决方法是使用 typedef 定义一次自定义类型,然后在两个地方引用它。这里我将 MyType 定义为

null | string | number
,然后我将该类型用于私有类字段 #x 和函数参数。

// @ts-check

/**
 * @typedef MyType
 * @type {null | string | number}
 */

class C {
    /** @type {MyType} */
    #x = null;

    /** @type {(x: MyType) => void} */
    f(x) {
        console.log(this.#x)
    };
};
© www.soinside.com 2019 - 2024. All rights reserved.