Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't access object values using keys in Typescript (TS )

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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])
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading