第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

typescript 類型兼容問(wèn)題

typescript 類型兼容問(wèn)題

慕森王 2019-03-27 20:14:12
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: []) { }現(xiàn)在我定義了兩個(gè)interface,他們之間的value類型不一樣,一個(gè)是string,另一個(gè)是數(shù)組但是我需要在forEach里面根據(jù)lable的類型分別傳值另外兩個(gè)函數(shù),這兩個(gè)函數(shù)的參數(shù)類型不一樣,編輯器會(huì)提示報(bào)錯(cuò),有什么辦法兼容不同的類型嗎
查看完整描述

2 回答

?
守著一只汪

TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊

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

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

}

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

interface Input {

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

}

在使用的時(shí)候先判斷value的類型

if (value instanceof string[]){

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

}

就你問(wèn)的報(bào)錯(cuò)問(wèn)題,必須先明確item的類型,這樣就不會(huì)報(bào)錯(cuò):

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)
}

})


查看完整回答
反對(duì) 回復(fù) 2019-03-27
?
SMILET

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊

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[]) {

}


查看完整回答
反對(duì) 回復(fù) 2019-03-27
  • 2 回答
  • 0 關(guān)注
  • 574 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)