Get Optional

Challenge

Implement the advanced util type GetOptional<T>, which remains all the optional fields

For example

type I = GetOptional<{ foo: number; bar?: string }>; // expected to be { bar?: string }

Solution

Für die Lösung dieser Aufgabe muss man einfach die Kondition aus der Aufgabe Required umdrehen, um alle Keys zu finden, die optional sind.

type OptionalKeys<T> = {
  [Key in keyof T as Omit<T, Key> extends T ? Key : never]: T[Key];
};

References

Utility Types - Mapped Types