I am in the process of creating a function that takes an object as input and converts all number fields within that object to strings. My goal is for TypeScript to accurately infer the resulting object's fields and types, while also handling nested structures seamlessly.
Below is a snippet of the current implementation which lacks type safety:
import _ from 'lodash'
export const numbersToString = <T extends object>(obj: T) => {
obj = _.cloneDeep(obj)
_.keys(obj).forEach((key) => {
if (_.isNumber(obj[key])) {
obj[key] = String(obj[key])
} else if (_.isArray(obj[key])) {
obj[key] = obj[key].map((el) => (_.isObject(el) ? numbersToString(el) : el))
} else if (_.isObject(obj[key])) {
obj[key] = numbersToString(obj[key])
}
})
return obj
}