Reputation: 171
I'm attempting to write a function the converts the keys of an object from camelCase to snake_case in TypeScript. This is my code:
private convertToSnakeCase (obj: object): object{
const snakeCasedObject: object = {};
Object.keys(obj).map((key: string) => {
const snakeCaseKey: string = _.snakeCase(key);
snakeCasedObject[snakeCaseKey] = obj[key];
});
return snakeCasedObject;
}
The TypeScript compiler throws the following error:
[ts] Element implicitly has an 'any' type because type '{}' has no index signature.
Is it possible to write a function like this without using an explicit any
type? I would think that you could because the object keys should always be strings?
Upvotes: 0
Views: 52
Reputation: 1867
It depends on how specific you want. One solution is to do something like
type AnyObj = {[key: string]: any};
private convertToSnakeCase(obj: AnyObj): AnyObj {
// ...
}
I assume you just want obj
to be an actual object, which is why you want to avoid any
, not because you want to avoid any
at all costs.
Upvotes: 1