Search code examples
typescripttypestypescript-typingstypescript-types

Typescript: Excluding all required properties from a type


How do I have to define in the following code type ExcludeAllRequiredProps<T> to exclude (like the name says) all required properties? Thanks in advance.

type A = {
  a: number,
  b: number,
  c?: number,
  d?: number
}

type B = ExcludeAllRequiredProps<A>


// B shall be { c?: number, d?: number }

[Edit - a while later]

Do you consider this a proper solution?

type ExcludeAllRequiredProps<T> = {
  [K in keyof T]?: T extends Record<K, T[K]> ? never : T[K]
}

Solution

  • Your solution is close, but it keeps those extra keys along, which might cause confusion even if they are of type never. This solution will remove the unwanted keys from the result:

    type ExcludeAllRequiredProps<T> = Pick<T, {
        [K in keyof T]-?: T extends Record<K, T[K]> ? never : K
    }[keyof T]>
    
    type A = {
        a: number,
        b: number,
        c?: number,
        d?: number
    }
    
    type B = ExcludeAllRequiredProps<A> // { c?: number, d?: number }