【问题标题】:Generate a type where each nullable value becomes optional生成一个类型,其中每个可为空的值都变为可选
【发布时间】:2020-02-13 00:23:03
【问题描述】:

我有一个这样的类型:

interface A {
  a: string
  b: string | null
}

我想生成相同的类型,但每个可为空的值都变成可选的:

interface A {
  a: string
  b?: string | null
}

类似的东西,但仅适用于可为空的值(这使得所有值都是可选的):

export type NullValuesToOptional<T> = {
  [P in keyof T]?: T[P]
}

【问题讨论】:

  • 你是专门找b?: string | null,还是b: string | null | undefined也可以?
  • @Rengers 我真的需要一个带有可选值的类型,即:b?: string | null

标签: typescript null mapped-types


【解决方案1】:

提取可为空的字段键,然后根据该信息生成新类型。
This answer 删除 never 类型是解开谜题的关键。

interface A {
  a: string
  b: string | null
  c?: string | null;
  d?: string;
}

// Built-in NonNullable also catches undefined
type NonNull<T> = T extends null ? never : T;
type NullableKeys<T> = NonNullable<({
  [K in keyof T]: T[K] extends NonNull<T[K]> ? never : K
})[keyof T]>;

type NullValuesToOptional<T> = Omit<T, NullableKeys<T>> & Partial<Pick<T, NullableKeys<T>>>;

type B = NullValuesToOptional<A>;

不过,并不像我希望的那样直截了当。

【讨论】:

  • 非常感谢您的回答!我编辑您的代码只是为了给类型添加一个名称。我以为我可以转换这段代码以使其递归,但我做不到。我刚刚为此创建了一个新问题:stackoverflow.com/questions/58411991/…。如果您有答案,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-02
  • 1970-01-01
  • 2021-07-01
  • 2015-02-01
  • 2015-03-12
  • 2021-01-16
相关资源
最近更新 更多