kaylanx
kaylanx

Reputation: 908

TypeScript: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

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

Upvotes: 7

Views: 41693

Answers (3)

Nicholas Tower
Nicholas Tower

Reputation: 84902

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, which leaves typescript in charge of inferring the type, but instructs it to infer it as strictly as possible:

const dayKey = 'monday' as const;

Upvotes: 22

KushalSeth
KushalSeth

Reputation: 4629

Prefer to use particular data-types. but in few cases, where you get dynamic response, you can declare like this:

let obj = Array<any>()

Upvotes: 0

Lionel Rowe
Lionel Rowe

Reputation: 5926

You can use TypeScript's keyof keyword for this:

const dayKey: keyof Schedule = 'monday'

Upvotes: 8

Related Questions