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

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

選擇函數在打字稿中接受字符串或數組

選擇函數在打字稿中接受字符串或數組

滄海一幻覺 2021-06-30 05:15:47
我想用打字稿寫這個函數:const pick = (obj, keys) => {  if (!Array.isArray(keys)) keys = keys.split(',')  return keys.reduce((acum, key) => (acum[key] = obj[key], acum), {})}const o = {  a: 1,  b: 2,  c: 3}console.log('o[a,c]:', pick(o, 'a,c'))        // { a: 1, c: 3 }console.log('o[a,c]:', pick(o, ['a', 'c']))   // { a: 1, c: 3 }我已經看到這個答案,這似乎是一個很好的起點,但我不知道如何將字符串轉換為 K[]?;蛘呶铱梢砸阅撤N方式告訴 Typescript 相信我,并且不要檢查類型嗎?
查看完整描述

2 回答

?
ibeautiful

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

打字稿編譯器不知道當您使用拆分評估字符串時您的字符串將是什么,因此您必須強制K[]使用它,這將返回T.


根據您所需的用途,只有第二個才能獲得所需的類型。


// i changed the "a" property to a string

const o = { a: 'hello', b: 2, c: 3 };


// <T, K extends keyof T> - here you assign the generics

// T - will be used on "obj" parameter so it can inherit it's properties

// K - will be a property of T

// I typed the "keys" parameter with "string" (to respect your first usage) and K[] (an array of K properties , for the second one)

// At last, we want the function to return K props of T, we have the Pick construct for that.

const pick = <T, K extends keyof T>(obj: T, keys: string | K[]): Pick<T, K> => {

    if (!Array.isArray(keys)) keys = (keys as string).split(',') as K[]; // we know that "keys" is a string, so we'll force the type on it, and we'll force K[] on the .split result, this will return all types from T.

    return keys.reduce((acum, key: K) => (acum[key] = obj[key], acum), {} as T ); // here we mark the accumulator as T, so we know what properties are used.

};


let p1 = pick(o, 'a,c'); // { a: string , b: number, c: number } - You'll get all the keys from obj

let p2 = pick(o, ['a','c']); // { a: string , c: number }


查看完整回答
反對 回復 2021-07-01
?
紅糖糍粑

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

你可以使用聯合


const pick = (obj: Object,  keys: string[] | string) => {

....

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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