typescript - 在类本身内部为 ES6 类使用类型

标签 typescript webstorm typescript-typings

我有一个像这样的现有 ES6 类 ClassA.js:

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

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

我还有一个打字文件 ClassA.d.ts

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

我还有一个 index.js

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

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

正如预期的那样,使用 WebStorm 时会出现编译器错误,因为 test 需要 string

但是,我没有收到 ClassA.js 中缺少参数的 this.test() 的警告。此外,如果调用 this.(1) 不会引发警告。

有没有办法在类本身内部也有警告?我还可以使用 tsc 来包含 ClassA.js 并在 index.jsClassA 中获取错误类的编译器警告.js?

最佳答案

类型不应该用于检查库本身,您不能让 IDE(或 tsc 编译器)将它们用于此目的。 我建议改用 JSDoc 注释,例如:

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

关于typescript - 在类本身内部为 ES6 类使用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56585031/

相关文章:

typescript - 为什么 TypeScript 允许在没有警告的情况下从字符串转换为数字

angular - 如何从 Angular Material 日期选择器更改日期?

less - 如何在 WebStorm 中为嵌入式 LESS 样式启用语法高亮显示?

TypeScript:读取对象中值的通用类型

reactjs - 如何为 React props 定义 TypeScript 类型,其中仅当 prop A 传递给组件时才接受 prop B?

javascript - 在选定区域插入新节点时,Slate.js 会引发错误

javascript - WebStorm 对 ExtJ 的支持

phpstorm - 如何在 WebStorm 或 PhpStorm 中更改 ${USER} 值?

typescript - 在定义中为类方法起别名

typescript - TypeScript 编译时如何检查 Omit?