首頁  >  問答  >  主體

錯誤:“‘string | string’類型的參數不可指派給‘string’類型的參數”

<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粉232409069P粉232409069420 天前483

全部回覆(1)我來回復

  • P粉322106755

    P粉3221067552023-08-26 10:17:11

    路由參數可以包含許多具有相同鍵的值。這就是為什麼它可能是字串數組而不是單一字串。如果你確定只有一個參數,你可以使用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;
    }

    回覆
    0
  • 取消回覆