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

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

通過值數組定義接口

通過值數組定義接口

慕碼人2483693 2023-04-01 16:08:53
如果我有一個帶有輸入道具的常量和一個返回輸入 ID 及其默認值的函數,如下所示:const Inputs = [{label: "myInput1", id: "myId1"}, {label: "myInput2" , id: "myId2" }]     const getInputValues = () => Inputs.reduce( (acc, item) => ({...acc, [item.id] : 123  }), {} )如何定義getInputValuesTypeScript 的返回類型?代碼
查看完整描述

2 回答

?
紫衣仙女

TA貢獻1839條經驗 獲得超15個贊

我能想到的唯一方法是對常量使用 const 斷言Inputs:


const Inputs = [

  {label: "myInput1", id: "myId1"},

  {label: "myInput2", id: "myId2"},

] as const;


type InputIds = typeof Inputs[number]['id'];


function getInputValues(): Record<InputIds, number> {

  return Inputs.reduce((acc, item) => {

    return {...acc, [item.id]: 123};

  }, {} as Partial<Record<InputIds, number>>) as Record<InputIds, number>;

}


查看完整回答
反對 回復 2023-04-01
?
慕工程0101907

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

您所能期望的最好的是Record<string, number>。

const?getInputValues?=?():Record<string,number>?=>?
????Inputs.reduce(?(acc,?item)?=>?({...acc,?[item.id]?:?123??}),?{})

為了更好的類型安全,您可以選擇Record<string, number | undefined>強制您對訪問的任何值進行類型檢查。


查看完整回答
反對 回復 2023-04-01
  • 2 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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