【问题标题】:VueJS, this.$route.query.page, and Type 'null' is not assignable to type 'string'VueJS、this.$route.query.page 和 Type \'null\' 不可分配给 type \'string\'
【发布时间】:2022-08-04 22:14:03
【问题描述】:

我已经为此工作了大约2个小时,但无济于事。我搜索了互联网,尝试创建条件等。

所以我在 VueJS 组件中有一个方法,如下所示:

paginate() {
  const test = this.$route.query.page;
  console.log(test);
  this.currPage = parseInt(test);
}

最后一行的单词 \"test\" 有一个红色下划线,我收到一条错误消息:

常量测试:LocationQueryValue |位置查询值[]

\'LocationQueryValue | 类型的参数LocationQueryValue[]\' 不可分配给 \'string\' 类型的参数。

类型 \'null\' 不可分配给类型 \'string\'.Vetur(2345)

我应该如何在不编辑 TypeScript 配置文件的情况下解决 TypeScript 错误?

    标签: typescript vue.js


    【解决方案1】:

    这意味着test 可以是null。它的类型很可能是string | null,它是一个联合类型。您需要对其进行测试以消除null 的情况。

    例如

    paginate() {
      const test = this.$route.query.page;
      console.log(test);
    
      if (typeof test === 'string') {
        // `test` has type string here because of the predicate.
        this.currPage = parseInt(test);
      }
    }
    

    Playground Link

    请注意,上述解决方案虽然确实正确,但改变了原始代码的含义,如果test 不是字符串,则保持this.currPage 不变。

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 2021-08-27
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 2019-02-08
      • 2022-11-15
      相关资源
      最近更新 更多