ffx292
ffx292

Reputation: 701

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:

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?

Upvotes: 1

Views: 1835

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370859

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

Upvotes: 1

Related Questions