Answer a question

I have been working on this for about 2 hours now, no to avail. I have searched the Internet, tried creating a condition, etc.

So I have a method in a VueJS component that looks like this:

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

The word "test" on the last line has a red underline and I get an error message saying this:

const test: LocationQueryValue | LocationQueryValue[]

Argument of type 'LocationQueryValue | LocationQueryValue[]' is not assignable to parameter of type 'string'.

Type 'null' is not assignable to type 'string'.Vetur(2345)

How should I solve the TypeScript error without editing the TypeScript configuration file?

Answers

It means test can be null. Its type is likely string | null which is a union type. You need test it to eliminate the null case.

For example

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

Please note that the above solution, while indeed proper, changes the meaning of the original code, leaving this.currPage unchanged if test is not a string.

Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐