[英]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我正在开发一个 Vue 项目,在使用 Reset Password 组件时也使用 TypeScript 和 axios 进行 API 调用,我在 auth.ts 文件中的 resetPassword 函数看起来像这样
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在我的 ResetPassword.vue 文件中,我使用的是 newPassword,如下所示
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'."在我的 ResetPassword.vue 文件中,第 3 个参数我收到一条错误消息,提示“类型‘string[]’不可分配给类型‘string’”。
I'm a little new to ts and i needed a little help with it.我对 ts 有点陌生,我需要一些帮助。
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()我在这里的 2 个解决方案之间感到困惑,我应该这样做。$route.params.id 作为字符串还是这样做更好。$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[]
如果你确定,只有一个参数可以
as string
来基本上告诉打字稿编译器你知道这个变量 100% 是一个string
而不是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()
如果你将使用
.toString()
并且会有一个像["foo", "bar"]
这样的数组,你会得到"foo,bar"
作为.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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.