CookieEater
CookieEater

Reputation: 2496

Modify part of union type

Given an interface like this, is it possible to create a type or code that converts the null into undefined?

interface A {
  name: string
  foo: string | null
  bar: number | null
}

For example, I'd like to turn this into:

interface A {
  name: string
  foo: string | undefined
  bar: number | undefined
}

This seemed simple to me at first, but I couldn't find a way to target each props having type | null and convert it.

Upvotes: 1

Views: 465

Answers (1)

kaya3
kaya3

Reputation: 51034

This is a job for distributive conditional types. They distribute over unions, so a type which simply maps null to undefined while leaving everything else alone will do what you want.

type NullToUndefined<T> = T extends null ? undefined : T
type MapNullToUndefined<T> = {[K in keyof T]: NullToUndefined<T[K]>}

Example usage:

// type Test1 = string | undefined
type Test1 = NullToUndefined<string | null>

// type Test2 = {a: string | undefined, b: number | undefined, c: boolean}
type Test2 = MapNullToUndefined<{a: string | null, b: number | null, c: boolean}>

Playground Link

Upvotes: 3

Related Questions