VueJS、this.$route.query.page 和类型“null”不可分配给类型“string”

erl*_*go3 2 typescript vue.js

我已经为此工作了大约 2 个小时,但毫无效果。我在网上搜索过,尝试创建条件等。

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

paginate() {
  const test = this.$route.query.page;
  console.log(test);
  this.currPage = parseInt(test);
}
Run Code Online (Sandbox Code Playgroud)

最后一行的“test”一词有红色下划线,我收到一条错误消息:

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

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

类型“null”不可分配给类型“string”。Vetur(2345)

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

Alu*_*dad 6

意思就是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);
  }
}
Run Code Online (Sandbox Code Playgroud)

游乐场链接

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