生成一个类型,其中每个可为 null 的值都变为可选 [英] Generate a type where each nullable value becomes optional

查看:50
本文介绍了生成一个类型,其中每个可为 null 的值都变为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的类型:

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

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

I would like to generate the same type but each nullable value becomes optional:

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

类似的东西,但只适用于可空值(这个使所有值都可选):

Something like that but only for nullable values (this one makes all values optional):

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

推荐答案

提取可为空的字段键,然后根据该信息生成新类型即可.
这个关于删除 never 类型的答案是解开谜题的关键.

Extracting the nullable field keys and then generating a new type based on that information would work.
This answer on removing never types holds the key to the puzzle.

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>;

虽然没有我希望的那么直接.

Not as straight-forward as I'd have hoped, though.

这篇关于生成一个类型,其中每个可为 null 的值都变为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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