Say I want to create a type from another type but change all number
s to string
s.
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 }
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.