1

I have a simple object like so:

export const daysOfTheWeek = {
  0: "Sunday",
  1: "Monday",
  2: "Tuesday",
  3: "Wednesday",
  4: "Thursday",
  5: "Friday",
  6: "Saturday",
};

I'm trying to access it by using a variable like so:

const checkDay = (dayIndex: number):void => {
  console.log(daysOfTheWeek[dayIndex]) // error happens here
};

I'm expecting to log "Sunday", however I get this error that keeps popping up:

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

Any advice on how to fix this?

1 Answer 1

1

You need to tell TypeScript that the dayIndex: number is not actually just a number, but one of the daysOfTheWeek keys.

const checkDay = (dayIndex: keyof typeof daysOfTheWeek):void => {
  console.log(daysOfTheWeek[dayIndex])
};

If you can't do that, then you'll have to narrow inside the function

const checkDay = (dayIndex: number):void => {
  if (dayIndex !== 1 && dayIndex !== 2 ...) {
    throw new Error('Not a day of the week');
  }
  console.log(daysOfTheWeek[dayIndex])
};

or assert it after checking ranges:

const checkDay = (dayIndex: number):void => {
  if (!Number.isInteger(dayIndex) || dayIndex < 0 || dayIndex > 6) {
    throw new Error('Not a day of the week');
  }
  console.log(daysOfTheWeek[dayIndex as keyof typeof daysOfTheWeek])
};
Sign up to request clarification or add additional context in comments.

1 Comment

Great, I went with the third option of asserting it as dayIndex has to be a number.

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.