【问题标题】:How to omit optional properties from type?如何从类型中省略可选属性?
【发布时间】:2021-09-16 07:24:01
【问题描述】:

给定一个具有可选属性的对象类型,例如:

interface Person {
  name: string;
  age: number;
  friends?: Person[];
  jobName?: string;
}

…我想删除它的所有可选属性,结果是:

interface Person {
  name: string;
  age: number;
}

我该怎么做?


请注意,我不能使用Omit<Person, "friends" | "jobName">,因为事先不知道实际属性。我必须以某种方式收集所有可选属性的键的联合:

type OptionalKey<Obj extends object> = {
  [Key in keyof Obj]: /* ... */ ? Key : never;
}[keyof Obj];

type PersonOptionalKey = OptionalKey<Person>;
// "friends" | "jobName"

另外,typescript remove optional property 名字不好,没有回答我的问题。

【问题讨论】:

标签: typescript properties conditional-types


【解决方案1】:

虽然proposed in the comments 方法删除了可选属性,但它也删除了具有undefined 作为其类型的可能值的非可选属性。

interface Person {
    required: string;
    optional?: string;
    maybeUndefined: string | undefined
}

/*
type A = { required: string }
*/
type A = ExcludeOptionalProps<Person>

如果您正在寻找一种帮助类型删除 only optional 键,您可以将其写为:

type RequiredFieldsOnly<T> = {
    [K in keyof T as T[K] extends Required<T>[K] ? K : never]: T[K]
}

playground link

【讨论】:

    猜你喜欢
    • 2019-09-06
    • 1970-01-01
    • 2021-07-06
    • 2020-09-21
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多