【问题标题】:How to get linter/compiler warning when comparing function without call?在没有调用的情况下比较函数时如何获得 linter/compiler 警告?
【发布时间】:2019-06-15 08:02:23
【问题描述】:

我在编写打字稿代码时经常犯这种错误:

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 或编译器警告?

【问题讨论】:

  • 另外,我认为你的例子是错误的。 foo.isBar 是吸气剂,而不是 foo.isFoo
  • 哦,我交换了 foo 和 bar 忘记将 getter 移动到 foo。
  • 我删除了我的评论以支持我的回答。

标签: typescript linter


【解决方案1】:

这是不可能的,条件句中的语法是 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 或编译器都不会抛出错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-29
    • 2013-12-22
    • 1970-01-01
    • 2022-01-05
    • 2021-11-22
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多