Chris Seltzer
Chris Seltzer

Reputation: 171

How do you add types to a function that works on any objects keys without using any in TypeScript?

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

Answers (1)

c1moore
c1moore

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

Related Questions