I have a function that converts the case of a target string, array, or object from camel case to snake case.
convertCamelToSnake (target) {
// Complex logic to convert target depending on what type it is
return convertedTarget
}
I want to specify types on this function using a Generic like so:
convertCamelToSnake <T>(target: T):T {
// Complex logic to convert target depending on what type it is
return convertedTarget
}
This works for strings and arrays, but we convert the keys of a given object to snake case. But typescript doesn't realize this and assumes that the keys remain the same because we declare that we are returning T.
How can I retain the ability to know the type that is returned. I.e. string, array, object, while leaving the keys of the dictionary ambiguous?
For instance let's say we pass in:
const a = { helloWorld: "bob", age: 21 }
a = convertCamelToSnake(a); // { hello_world: "bob", age: 21 };
a.hello_world; // Property 'hello_world' does not exist on type
How can we make it so we're allowed to access the hello_world property after converting the object, while also still being able to infer that the return value is of type object (since we could for instance also be passing in an array into this function)?