Alexander
Alexander

Reputation: 1378

Element implicitly has an 'any' type because expression of type 'string'

Why do I get this error?

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ 0: string; 1: string; 2: string; 3: string; }'.
  No index signature with a parameter of type 'string' was found on type '{ 0: string; 1: string; 2: string; 3: string; }'.ts(7053)

this is my code: I specifically made the index a string so there should be no problem, but my StatusMap variable gives me this red flag..

 const getStatusMeaning = (index: string) => {
    const StatusMap = {
      '0': 'Unknown',
      '1': 'Pending',
      '2': 'Success',
      '3': 'Failure',
    }

    return StatusMap[index]
  }

Upvotes: 0

Views: 1012

Answers (3)

Orelsanpls
Orelsanpls

Reputation: 23495

As an alternative to @Paleo answer, If you want a strongly typed method, I would recommend the following :

const StatusMap = {
  '0': 'Unknown',
  '1': 'Pending',
  '2': 'Success',
  '3': 'Failure',
};

const getStatusMeaning = (index: keyof typeof StatusMap): string => {
  return StatusMap[index];
}

enter image description here

Upvotes: 2

Ján Jakub Naništa
Ján Jakub Naništa

Reputation: 1916

If you account for the fact that some strings do not exists as keys in your status map you can let TypeScript know that your map is a string record:

const StatusMap: Record<string, string> = {

The other solution is to be more specific about the index and only allow the supported indexes instead of any string.

Upvotes: 1

Paleo
Paleo

Reputation: 23682

You can define the proper type for index:

const getStatusMeaning = (index: '0' | '1' | '2' | '3') => {
  // Your implementation here
}

Or, use a dictionary type { [key: string]: string }:

const getStatusMeaning = (index: string) => {
  const StatusMap: { [key: string]: string } = {
    '0': 'Unknown',
    '1': 'Pending',
    '2': 'Success',
    '3': 'Failure',
  }

  return StatusMap[index]
}

Upvotes: 2

Related Questions