打字稿:如何仅从类型中提取可选键?

Jus*_*ake 3 typescript

假设我有一个这样的类型:

type User = {
  uid: string,
  displayName?: string,
  bestFriend?: string,
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用某种映射类型从我的用户类型中提取可选属性?我正在寻找如何定义以下 OptioanlProperties<T>类型。

type OptionalUserProperties = OptionalProperties<User>
// type OptionalUserProperties = "displayName" | "bestFriend"
Run Code Online (Sandbox Code Playgroud)

我的用例是计算UpdateOf<User>允许特定“操作”值的类型,例如DeleteProperty将其分配给基本类型中可选的键。

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] }
Run Code Online (Sandbox Code Playgroud)

Kar*_*ski 10

是:

type OptionalPropertyOf<T extends object> = Exclude<{
  [K in keyof T]: T extends Record<K, T[K]>
    ? never
    : K
}[keyof T], undefined>
Run Code Online (Sandbox Code Playgroud)

  • 这比链接重复问题中的解决方案简洁得多。谢谢你。 (3认同)
  • 事实上,这个解决方案感觉也更好。 (2认同)

归档时间:

查看次数:

882 次

最近记录:

6 年,11 月 前