I'd like to map an object recursively so that the primitive values in the object are converted to some other type.
For example, I'd like an object like this:
const before = { a: { c: '' }, b: [ '', { d: '' } ] }
to become this:
const after = { a: { c: Test }, b: [ Test, { d: Test } ] }
I'm also assuming that values won't be Date, Symbol, or null/void. Just JSON serializable types like string, numbers, etc. (except null)
Here's what I tried:
type ConvertToTest<T> = {
[P in keyof T]: T[P] extends any[]
? ConvertToTest<T[P]>
: T[P] extends {}
? ConvertToTest<T[P]>
: Test;
}
function convert<T>(o: T): ConvertToTest<T> {
// ...
}
This is using the conditional types introduced in Typescript 2.8.
const after = convert(before) results in after.a.c with string type completions in the editor for c, instead of completions for Test.
How do I rewrite type ConvertToTest<T> to convince Typescript that after.a.c is of type Test?
EDIT: Here's a Typescript Playground link illustrating the above.