Search code examples
typescriptwebstormtypescript-typings

Use typings for ES6 class inside class itself


I have an existing ES6 class ClassA.js like this:

module.exports = class A {
  test(param) {
    console.log(param)
  }

  test2(param) {
    this.test() // no warning here
  }
}

Also I have a typings file ClassA.d.ts

export type A = {
  test(param: string): void
  test2(param: string): void
}

Also I have an index.js

const A = require('./ClassA');

const a = new A();
a.test(1);

This as expected gives an compiler error using WebStorm as test expects a string.

However I don't get a warning for this.test() inside ClassA.js which is lacking the param. Also if calling this.(1) doesn't throw a warning.

Is there a way to have warnings also inside the class itself? Also can I use tsc to include ClassA.js and get a compiler warning for wrong class in index.js and also inside ClassA.js?


Solution

  • Typings are not supposed to be used for linting the libraries themselves, you can't make the IDE (or tsc compiler) to use them for this purpose. I'd suggest using JSDoc annotations instead, like:

    module.exports = class A {
        /**
         * @param {string} param
         */
        test(param) {
            console.log(param)
        }
        /**
         * @param {string} param
         */
        test2(param) {
            this.test() // no warning here
        }
    }