Search code examples
typescriptpropertiesconditional-types

How to omit optional properties from type?


Given an object type that has optional properties, such as:

interface Person {
  name: string;
  age: number;
  friends?: Person[];
  jobName?: string;
}

… I'd like to remove all of its optional properties so that the result is:

interface Person {
  name: string;
  age: number;
}

How can I do that?


Please, note that I can't use Omit<Person, "friends" | "jobName"> because the actual properties are not known in advance. I have to somehow collect the union of keys of all optional properties:

type OptionalKey<Obj extends object> = {
  [Key in keyof Obj]: /* ... */ ? Key : never;
}[keyof Obj];

type PersonOptionalKey = OptionalKey<Person>;
// "friends" | "jobName"

Also, typescript remove optional property is poorly named and doesn't answer my question.


Solution

  • While the method proposed in the comments removes optional properties it also removes non-optional properties having undefined as a possible value of their type.

    interface Person {
        required: string;
        optional?: string;
        maybeUndefined: string | undefined
    }
    
    /*
    type A = { required: string }
    */
    type A = ExcludeOptionalProps<Person>
    

    In case you're looking for a helper type removing only optional keys you may write it as:

    type RequiredFieldsOnly<T> = {
        [K in keyof T as T[K] extends Required<T>[K] ? K : never]: T[K]
    }
    

    playground link