我有一个像这样的现有 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.js
和 ClassA 中获取错误类的编译器警告.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/