Home > Blockchain >  VueJS, this.$route.query.page, and Type 'null' is not assignable to type 'string'
VueJS, this.$route.query.page, and Type 'null' is not assignable to type 'string'

Time:05-24

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?

CodePudding user response:

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

  • Related