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
The error "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type" occurs when we use a string to index an object with specific keys. To solve the error, type the string as one of the object's keys.
The error "Element implicitly has 'any' type because index expression is not of type 'number'" occurs when an array is indexed with a value that is not a number. To solve the error, use an object if storing key-value pairs or use a type assertion.
The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.
In typescript, Index Signature identifies key type for indexing of an object. Everytime an object in typescript is created and indexing is expected on that object then developers must specify Index Signature .
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;
You can use TypeScript's keyof
keyword for this:
const dayKey: keyof Schedule = 'monday'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With