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

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

當存在另一個屬性時,將可選屬性設為必需

當存在另一個屬性時,將可選屬性設為必需

長風秋雁 2023-07-06 18:21:59
我有如下所示的 proptypesinterface Props {resource: string;create?: boolean;route?: string;}從上面可以看出,create 和route 是可選的props。但是,我想實現這樣的類型:如果存在 create prop,則現在必須需要路由。有人知道如何做到這一點嗎?
查看完整描述

3 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

您應該對這些道具進行分組,并將分組的道具設為可選


interface RouteProps{

create: boolean;

route: string;

}


interface Props {

resource: string;

routeInfo?: RouteProps;

}


查看完整回答
反對 回復 2023-07-06
?
喵喵時光機

TA貢獻1846條經驗 獲得超7個贊

您可以將其拆分為兩種類型的聯合并create與文字類型一起使用:


type Props = {

  resource: string;

  create?: false;

  route?: string

} | {

  resource: string;

  create: true;

  route: string;

}


查看完整回答
反對 回復 2023-07-06
?
莫回無

TA貢獻1865條經驗 獲得超7個贊

實際上,您可以選擇使用打字稿執行類似的操作:


這可能就是您正在尋找的。但你必須明確設置TArgs<true>


type TArgs<T extends boolean> = {

   a: T,

   b: string,

   c: T extends true ? string : null

 }

使用工廠函數的示例:


type TArgs<T extends true | false> = {

    a: T,

    c?: T extends true ? string : null

}


const argsFactory = <T extends boolean>(a: T, c: T extends true ? string : null): TArgs<T> => {

    return {

        a,

        c

    }

}


// Works

argsFactory(true, "string");

argsFactory(false, null);


// Doesnt Work

argsFactory(false, "some String");

argsFactory(true, null)


查看完整回答
反對 回復 2023-07-06
  • 3 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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