Home > Mobile >  Converting types that are part of a union type
Converting types that are part of a union type

Time:10-27

Say I want to create a type from another type but change all numbers to strings.

This for example:

type NumberToString<T> = {
  [K in keyof T]: T[K] extends number ? string : T[K]
}

will work for an input:

type T = {
  num: number,
}

// works, creates new type { num: string }
type NewType = NumberToString<T1>;

but will fail if the number is part of a union like 'number | null'

type T = {
  maybeNum: number | null,
}

// not working as I expect
type NewType = NumberToString<T>;

Expected this

type T = { maybeNum: string | null }

Got this

type T = { maybeNum: number | null }

Typescript playground

CodePudding user response:

Do the extends the other way, then add in the types that aren't number:

type NumberToString<T> = {
  [K in keyof T]: number extends T[K] ? string | Exclude<T[K], number> : T[K]
};

However, number literal types don't work anymore:

type T = NumberToString<{ foo: 0 }> // { foo: 0 } instead of { foo: string }

but if you need this, lemme know and I'll edit in a workaround.

Playground

  • Related