打字稿:如何仅从类型中提取可选键? [英] Typescript: How to extract only the optional keys from a type?

查看:32
本文介绍了打字稿:如何仅从类型中提取可选键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a type like this:

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

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

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"

我的用例是计算一个 UpdateOf 类型,它允许特定的操作"值,例如 DeleteProperty 分配给基本类型中可选的键.

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] }

推荐答案

是:

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

这篇关于打字稿:如何仅从类型中提取可选键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆