4
votes

I'm converting my react app from JavaScript to TypeScript trying to figure out how I can address the following errors

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Schedule'. No index signature with a parameter of type 'string' was found on type 'Schedule'.

This is the code...

  export interface Schedule {
    display: Display;
    monday: Day;
    tuesday: Day;
    wednesday: Day;
    thursday: Day;
    friday: Day;
    saturday: Day;
    sunday: Day;
  }

  export interface Diary {
    schedule: Schedule;
    appointments: Array<Appointment>;
  }

 // ...

 const dayKey: string = 'monday'
 const day: Day = diary.schedule[dayKey]  // <-- Here is the error

 // ...

Previously as the data structure I was working with in JavaScript was just json this worked a treat, but I'm struggling to understand how to acheive the same thing with TypeScript.

Thanks

2

2 Answers

14
votes
const dayKey: string = 'monday';

The type on this is string, which is too general. Not every string has an entry in the schedule object. You and i know that when you do diary.schedule[dayKey] the only possible thing that could be accessing is "monday", but that's not available in the type information that typescript is working with.

You have several options of more specific types. You could specify that it's one of the keys in Schedule:

const dayKey: keyof Schedule = 'monday';

Or you could specify that it's specifically "monday"

const dayKey: 'monday' = 'monday';

Another way to specify that it's specifically "monday" is like this:

const dayKey = 'monday' as const;
3
votes

You can use TypeScript's keyof keyword for this:

const dayKey: keyof Schedule = 'monday'