首页 > 其他分享 >[Typescript] Clean type

[Typescript] Clean type

时间:2023-03-01 22:33:06浏览次数:38  
标签:acc Typescript return key Clean picked obj type

const pick = <TObj, TKeys extends (keyof TObj)[]>(obj: TObj, picked: TKeys) => {
  return picked.reduce((acc, key) => {
    acc[key] = obj[key];
    return acc;
  }, {} as Pick<TObj, TKeys[number]>);
};

Notice that TKeysis ("a" | "b")[], which is not really good, better to be "a" | "b".

 

Updated:

const pick = <TObj, TKeys extends keyof TObj>(obj: TObj, picked: TKeys[]) => {
  return picked.reduce((acc, key) => {
    acc[key] = obj[key];
    return acc;
  }, {} as Pick<TObj, TKeys>);
};

标签:acc,Typescript,return,key,Clean,picked,obj,type
From: https://www.cnblogs.com/Answer1215/p/17170159.html

相关文章