Deep Omit with typescript

后端 未结 3 622
梦谈多话
梦谈多话 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:29

    The answers here were inspiring. I had some small issues with TypeScript 4.0 that I was able to work out. I'm maintaining it as a gist: https://gist.github.com/ahuggins-nhs/826906a58e4c1e59306bc0792e7826d1. Hope this helps some people, especially those wanting to deal with Partial utility in a deep omit.

    /** Union of primitives to skip with deep omit utilities. */
    type Primitive = string | Function | number | boolean | Symbol | undefined | null
    
    /** Deeply omit members of an array of interface or array of type. */
    export type DeepOmitArray = {
        [P in keyof T]: DeepOmit
    }
    
    /** Deeply omit members of an interface or type. */
    export type DeepOmit = T extends Primitive ? T : {
        [P in Exclude]: //extra level of indirection needed to trigger homomorhic behavior
            T[P] extends infer TP ? // distribute over unions
            TP extends Primitive ? TP : // leave primitives and functions alone
            TP extends any[] ? DeepOmitArray : // Array special handling
            DeepOmit
            : never
    }
    
    /** Deeply omit members of an array of interface or array of type, making all members optional. */
    export type PartialDeepOmitArray = Partial<{
        [P in Partial]: Partial>
    }>
    
    /** Deeply omit members of an interface or type, making all members optional. */
    export type PartialDeepOmit = T extends Primitive ? T : Partial<{
        [P in Exclude]: //extra level of indirection needed to trigger homomorhic behavior
            T[P] extends infer TP ? // distribute over unions
            TP extends Primitive ? TP : // leave primitives and functions alone
            TP extends any[] ? PartialDeepOmitArray : // Array special handling
            Partial>
            : never
    }>
    

提交回复
热议问题