TypeScript Type-safe Omit Function

前端 未结 4 1835
余生分开走
余生分开走 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:17

    If we limit the type of keys to string [],It works. But it does not seem to be a good idea.Keys should be string | number | symbol[];

    function omit(
      obj: T,
      ...keys: K[]
    ): { [k in Exclude]: T[k] } {
      let ret: any = {};
      Object.keys(obj)
        .filter((key: K) => !keys.includes(key))
        .forEach(key => {
          ret[key] = obj[key];
        });
      return ret;
    }
    const result = omit({ a: 1, b: 2, c: 3 }, 'a', 'c');
    // The compiler inferred result as 
    // {
    //   b: number;
    // }
    

提交回复
热议问题