Deep Omit with typescript

后端 未结 3 626
梦谈多话
梦谈多话 2020-12-11 03:46

Is it possible to maintain type coverage on a function that deeply removes all instances of a key in an object?

My function looks like this.

function         


        
3条回答
  •  我在风中等你
    2020-12-11 04:10

    For those coming here with a later version of TS (I've tested this with TS3.8.3), you'll need to inline DeepOmitHelper from Titian's answer.

    type Primitive =
      | string
      | Function
      | number
      | boolean
      | Symbol
      | undefined
      | null;
    
    type DeepOmitArray = {
      [P in keyof T]: DeepOmit;
    };
    
    export type DeepOmit = T extends Primitive
      ? T
      : {
          [P in Exclude]: T[P] extends infer TP
            ? TP extends Primitive
              ? TP // leave primitives and functions alone
              : TP extends any[]
              ? DeepOmitArray // Array special handling
              : DeepOmit
            : never;
        };
    

提交回复
热议问题