Generate a type where each nullable value becomes optional

拜拜、爱过 提交于 2020-03-03 09:05:12

问题


I have a type like this one:

interface A {
  a: string
  b: string | 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]
}

回答1:


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.



来源:https://stackoverflow.com/questions/58409603/generate-a-type-where-each-nullable-value-becomes-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!