简体   繁体   中英

Error : " Argument of type 'string | string[]' is not assignable to parameter of type 'string' "

I'm working on a Vue project also using TypeScript and axios for API calls while working on a Reset Password component my resetPassword function in the auth.ts file looks like this

resetPassword(password1: string, password2: string, uid: string, token: string): Promise<any> {
      
      return new Promise<any>((resolve, reject) => {
        axios
            .post("API", { password1, password2, uid, token })
            .then((res : any) => {
              resolve(//RESOLVE);
            })
            .catch((error) => {
              //REJECT
            })
      })
    }

In my ResetPassword.vue file I'm using the newPassword as shown below

this.resetPassword(password1.value, password2.value, this.$route.params.id, this.$route.params.resetID).then(
      (res) => {
        if(password1.value == password2.value){
            Notification{
                "SUCCESS"
            });
          }

In my ResetPassword.vue file the 3rd param im getting an error saying "Type 'string[]' is not assignable to type 'string'."

I'm a little new to ts and i needed a little help with it.

I'm confused between 2 solution here should i do this.$route.params.id as string or is it better to do this.$route.params.id.toString()

The route params could contain many values with the same key. That is why it could be an array of strings rather than a single string. If you are sure, that there is only one param you can use as string to basically tell the typescript compiler that you know that this variable is 100% a string and not string[]

this.resetPassword(password1.value, password2.value, this.$route.params.id as string, this.$route.params.resetID as string)

If you will use .toString() and there will be an array like ["foo", "bar"] , you would get "foo,bar" as the result of .toString()

If you are unsure whether it is an array or not, you could check it, and if it is an array then take the first value:

let id: string;
if (Array.isArray(this.$route.params.id)) {
    id = this.$route.params.id[0];
} else {
    id = this.$route.params.id;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM