简体   繁体   中英

TypeScript - A computed property name must be of type 'string', 'number', 'symbol', or 'any'

I'm trying to use the computer property name feature in my typescript code as

import {camelCase} from "lodash";

const camelizeKeys = (obj:any):any => {
  if (Array.isArray(obj)) {
    return obj.map(v => camelizeKeys(v));
  } else if (obj !== null && obj.constructor === Object) {
    return Object.keys(obj).reduce(
      (result, key) => ({
        ...result,
        [camelCase(key)]: camelizeKeys(obj[key]),   // error on [camelCase(key)]
      }),
      {},
    );
  }
  return obj;
};

It's giving a compile time error as:

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts

I tried to resolve this error by following this SO thread , but no success.

Do you have the lodash typings?

npm install @types/lodash

If so and they still don't work, you may just have to assert the type of camelCase(key) :

[camelCase(key):string]: camelizeKeys(obj[key]),

As per the answer by @Klaycon. I installed the types, which give me a hint for the return type of camelCase(). Then I managed to solve the problem as

 [String(camelCase(key))]: camelizeKeys(obj[key]),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM