亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

typescript 類型兼容問題

typescript 類型兼容問題

楊__羊羊 2019-03-25 10:41:23
interface Select {     lable:string,    value:string[]  }interface Input {     lable: string     value :string}const arr =[     {         lable: "select",        value:['boy', 'gril']     },     {         lable: 'input',        value: 'this is a input'     } ]; arr.forEach((item: Select | Input) => {       if (item.lable =='input') {         reciverInputProps(item.value)     }else {         reciverSelectProps(item.value)     }      })function reciverInputProps(value: string) { }function reciverSelectProps(value: []) { }現在我定義了兩個interface,他們之間的value類型不一樣,一個是string,另一個是數組但是我需要在forEach里面根據lable的類型分別傳值另外兩個函數,這兩個函數的參數類型不一樣,編輯器會提示報錯,有什么辦法兼容不同的類型嗎
查看完整描述

2 回答

?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

可以在聲明時使用:value: string|string[],比如

function reciverSelectProps(value: string|string[]) {

}

你也可以在接口中這樣聲明:

interface Input {

lable: string;
value :string|string[];

}

在使用的時候先判斷value的類型

if (value instanceof string[]){

let v:string[]=value as string[];

}

就你問的報錯問題,必須先明確item的類型,這樣就不會報錯:

arr.forEach((item: Select | Input) => {

if (item.lable =='input') {    let vi:Input=item as Input;
    reciverInputProps(vi.value)
}else {    let si:Input=item as Select;
    reciverSelectProps(si.value)
}

})


查看完整回答
反對 回復 2019-03-25
?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

interface Select {
    lable: 'select',
    value: string[]
}interface Input {
    lable: 'input',
    value: string}const arr = [
    {
        lable: "select",
        value: ['boy', 'gril']
    },
    {
        lable: 'input',
        value: 'this is a input'
    }
];


arr.forEach((item: Select | Input) => {    if (item.lable == 'input') {
        reciverInputProps(item.value)
    } else {
        reciverSelectProps(item.value)
    }

})function reciverInputProps(value: string) {

}function reciverSelectProps(value: string[]) {

}


查看完整回答
反對 回復 2019-03-25
  • 2 回答
  • 0 關注
  • 430 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號