Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting types that are part of a union type

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading