TypeScript Type-safe Omit Function

前端 未结 4 1830
余生分开走
余生分开走 2021-02-08 20:00

I want to replicate lodash\'s _.omit function in plain typescript. omit should return an object with certain properties removed specified via parameter

4条回答
  •  隐瞒了意图╮
    2021-02-08 20:20

    The accepted answer from Nurbol above is probably the more typed version, but here is what I am doing in my utils-min.

    It uses the typescript built-in Omit and is designed to only support string key names. (still need to loosen up the Set to Set, but everything else seems to work nicely)

    export function omit>(obj: T, ...keys: K[]): Omit {
      let ret: any = {};
      const excludeSet: Set = new Set(keys); 
      // TS-NOTE: Set makes the obj[key] type check fail. So, loosing typing here. 
    
      for (let key in obj) {
        if (!excludeSet.has(key)) {
          ret[key] = obj[key];
        }
      }
      return ret;
    }
    

提交回复
热议问题