how to refer to a private class field in typescript jsdoc

55 Views Asked by At

Please tell me: how to refer to a private class field in typescript jsdoc?

script.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 ) { };

};
2

There are 2 best solutions below

0
lepsch On

This is an open issue in Typescript itself. But there is a workaround to get what you want.

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

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

One possible workaround is to use typedef to define a custom type once, then reference it in both places. Here I've used @typedef to define MyType as null | string | number, then I've used that type for both the private class field #x and the function parameter.

// @ts-check

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

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

    /** @type {(x: MyType) => void} */
    f(x) {
        console.log(this.#x)
    };
};