在编写打字稿代码时,我经常犯此类错误:
class Foo {
constructor() { }
public get isFoo(): boolean { return true; } // getter
public isBar(): boolean { return false; } // normal function
}
let foo = new Foo();
if (foo.isFoo) { // this is ok, getter returns true
console.log("it is foo");
}
// and here comes the mistake:
if (foo.isBar) { // <- isBar is defined, forgot to write ()
console.log("it is bar"); // this happens also
}
是否可以针对此类错误获得某种tslinter或编译器警告?
答案 0 :(得分:0)
这不是必要的,您条件中的语法是100%有效的
在某些用例中,您需要验证条件语句中方法的声明并运行一些代码块。
例如:
class Foo {
public isFoo(): boolean {
return true;
}
public get isBar(): boolean {
return false;
}
}
const fooInstance: Foo = new Foo();
if (foo.isFoo) {
console.log('Foo class has method isFoo');
}
if (!foo.isXyz) {
console.log('Foo class does not have method isXyz');
}
const fooMethod: () => boolean = foo.isFoo; // this is also valid syntax
在上面的示例中,这两种情况中的任何一种都没有linter或编译器会引发错误。