0

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]
  }
1
  • 1
    You're accept "hello" is a valid index. What do you think StatusMap["hello"] would produce? Certainly not any of these values, hence TS downgrades it to "any" (or upgrade, depending on how you look at it). Commented May 27, 2020 at 14:17

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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]
}

1 Comment

Note that getStatusMeaning('invalid key') won't display any error using the second method
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.