【问题标题】:Typescript: How to extract only the optional keys from a type? [duplicate]Typescript:如何仅从类型中提取可选键? [复制]
【发布时间】:2018-12-22 22:20:08
【问题描述】:

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

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

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

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

我的用例是计算允许特定的UpdateOf&lt;User&gt; 类型 “操作”值,例如 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] }

【问题讨论】:

    标签: typescript


    【解决方案1】:

    是的:

    type OptionalPropertyOf<T extends object> = Exclude<{
      [K in keyof T]: T extends Record<K, T[K]>
        ? never
        : K
    }[keyof T], undefined>
    

    【讨论】:

    • 这比链接重复问题中的解决方案要简洁得多。谢谢。
    • 确实这个解决方案也感觉更好。
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 2018-03-24
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多