How to omit optional properties from type?
09:08 05 Jul 2021

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 because the actual properties are not known in advance. I have to somehow collect the union of keys of all optional properties:

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

type PersonOptionalKey = OptionalKey;
// "friends" | "jobName"

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

typescript properties conditional-types