【问题标题】:Typescript does not detect condition in callback - VueTypescript 在回调中未检测到条件 - Vue
【发布时间】:2022-01-05 10:42:49
【问题描述】:

在我的 Vuex 商店的状态下,我有一个 foo 对象,它可能是 null。 因此,在访问其属性之一(例如id)之前,我必须检查this.$store.state.foo 是否不为空。

一直运行良好,但似乎 TypeScript 没有检测到 axios 回调中的条件:

private join(): void {
    if (this.$store.state.foo) { // <- condition to check that `this.$store.state.foo` is not null
      this.axios.post(`/foo/${this.$tstore.state.foo.id}/join`) // <- No error here
        .then((response) => {
          // ... some code
          this.$router.push({
            name: 'bar',
            params: { id: this.$tstore.state.foo.id } // <- TS error here, foo is potentially null
          });
        })
        .catch((error: AxiosError) => {
          // ... some code
        });
    }
  }

我显然可以再次检查this.$store.state.foo 在回调中是否不为空,但是有办法告诉 TypeScript 检测上限范围条件吗?

【问题讨论】:

  • 它不起作用,因为 vue 路由器期望参数不为空。这不是我的问题的重点:为什么 TypeScript 没有检测到上限范围内的条件?

标签: javascript typescript vue.js callback vuex


【解决方案1】:

您需要捕获您的变量 - TS 假定 foo 的值在回调运行时可能已变为未定义。

检查一个更简单的例子:

class X {
  foo: string | undefined;

  print = (x: string) => console.log(x);

  private join(): void {
    if (this.foo) { 
      setTimeout(() => {
        this.print(this.foo);   // ERROR
      }, 1000);
    }
  }

  private joinWithCapture(): void {
    const fooCapture = this.foo;
    if (fooCapture) { 
      setTimeout(() => {
        this.print(fooCapture); // OK
      }, 1000);
    }
  }
}

Playground

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多