Given a type how can I write a recursive mapped type that yields a type that is with all the same keys but with their types being strings instead of whatever their incoming type is? Specifically, I want to handle nested objects & arrays.
type MySourceType = {
field1 :string,
field2: number,
field3: number[],
field4: Date,
field5: {
nestedField1: number,
nestedField2: number[]
nestedField3: Date,
}
}
type MyDestinationType = MakeAllFieldsString<MySourceType>;
should yield:
type MyDestinationType = {
field1 :string,
field2: string,
field3: string[],
field4: string,
field5: {
nestedField1: string,
nestedField2: string[]
nestedField3: string,
}
}
this works for a regular "flat" object but fails to handle the nested objects and arrays
type JsonObject<T> = {[Key in keyof T]: string; }
I also tried this but it didn't seem work do what I expected either.
type NestedJsonObject<T> = {
[Key in keyof T]: typeof T[Key] extends object ? JsonObject<T[Key]> : string;
}
typeof” doing in your second try? Isn’t there an error there? Does it start working if you just removetypeof?Dateis an object type that you want to becomestringbut{a: number}is an object type that you don't want to becomestring, could you explain how you want the mapping to tell the difference between object types that you want to recurse into versus ones that you don't? Like, we could special-caseDate, but is that the only one?