Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: How to extract only the optional keys from a type? [duplicate]

Tags:

typescript

Let's say I have a type like this:

type User = {
  uid: string,
  displayName?: string,
  bestFriend?: string,
}

Is it possible to extract the optional properties from my User type using a mapped type of some kind? I'm looking for how to define the OptioanlProperties<T> type below.

type OptionalUserProperties = OptionalProperties<User>
// type OptionalUserProperties = "displayName" | "bestFriend"

My use-case is to compute an UpdateOf<User> type that permits specific "operation" values, like DeleteProperty to be assigned to keys that are optional in the base type.

export type UpdateOf<T> =
  // optional fields may be their own type, or the special DeleteProperty type.
  { [P in OptionalProperties<T>]?: T[P] | DeleteProperty } &
  // required fields may be changed, but cannot be deleted.
  { [P in Diff<keyof T, OptionalProperties<T>>]?: T[P] }
like image 906
Just Jake Avatar asked Dec 22 '18 22:12

Just Jake


1 Answers

Yes:

type OptionalPropertyOf<T extends object> = Exclude<{
  [K in keyof T]: T extends Record<K, T[K]>
    ? never
    : K
}[keyof T], undefined>
like image 131
Karol Majewski Avatar answered Sep 17 '22 15:09

Karol Majewski