错误:''string | string'类型的参数不可分配给'string'类型的参数”
P粉232409069
P粉232409069 2023-08-25 11:44:28
0
1
489
<p>我正在开发一个 Vue 项目,同时使用 TypeScript 和 axios 进行 API 调用,同时开发重置密码组件,我的 auth.ts 文件中的 resetPassword 函数如下所示</p> <pre class="brush:php;toolbar:false;">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 }) }) }</pre> <p>在我的 ResetPassword.vue 文件中,我使用如下所示的 newPassword</p> <pre class="brush:php;toolbar:false;">this.resetPassword(password1.value, password2.value, this.$route.params.id, this.$route.params.resetID).then( (res) => { if(password1.value == password2.value){ Notification{ "SUCCESS" }); }</pre> <p>在我的 ResetPassword.vue 文件中,第三个参数出现错误,提示<strong>“类型‘string[]’不可分配给类型‘string’。”</strong></p> <p>我对 ts 有点陌生,我需要一些帮助。</p> <p>我对这里的两种解决方案感到困惑,我应该将 <strong>this.$route.params.id 作为字符串</strong> <em>还是这样做更好</em> <strong>this.$ Route.params.id.toString()</strong></p>
P粉232409069
P粉232409069

全部回复(1)
P粉322106755

路由参数可以包含许多具有相同键的值。这就是为什么它可能是字符串数组而不是单个字符串。如果你确定只有一个参数,你可以使用 as string 来告诉打字稿编译器你知道这个变量 100% 是一个 string 而不是 字符串[]代码>

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

如果您将使用 .toString() 并且会有一个像 ["foo", "bar"] 这样的数组,您将得到 "foo ,bar" 作为 .toString()

的结果

如果不确定是否是数组,可以检查一下,如果是数组则取第一个值:

let id: string;
if (Array.isArray(this.$route.params.id)) {
    id = this.$route.params.id[0];
} else {
    id = this.$route.params.id;
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!