pmiranda
pmiranda

Reputation: 8420

Typescript, No index signature with a parameter of type 'string' was found on type '{}'

I have this function:

const fieldsOrder = [
  'boo',
];

fieldsOrder.reduce((sortedRequest, key) => {
  if (key in request)
    sortedRequest[key] = request[key]; // Here are the warnings
  return sortedRequest;
}

sortedRequest is an object, same with request, so I'm having that warning about using index in objects. In plain javascript works ok, how could I handle and modify the code to not have that warning?

I can't define sortedRequest or request as any or anything using any type, or Elinst will thrown an error (I can't changes that rule neither).

EDIT:

I've tried what tscpp answered. This is my code now:

export default function sortFields (
  request: Record<string, unknown>
): Partial<FeeLookupRequest> {
  return fieldsOrder.reduce((sortedRequest: Record<string, unknown>, key) => {
    if (key in request) {
      sortedRequest[key] = request[key];
    }
    return sortedRequest;
  }, {});
}

Now has no warnings.

Upvotes: 0

Views: 2586

Answers (1)

tscpp
tscpp

Reputation: 1566

The type of fieldsOrder is the type {}. The type {} have no keys. You need to type fieldsOrder with e.g object or Record<string, unknown> preferably.

Upvotes: 1

Related Questions