[英]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我正在将我的 React 应用程序从 JavaScript 转换为 TypeScript,试图弄清楚如何解决以下错误
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.以前我在 JavaScript 中使用的数据结构只是 json,这是一种享受,但我正在努力理解如何使用 TypeScript 实现同样的目标。
Thanks谢谢
const dayKey: string = 'monday';
The type on this is string
, which is too general.这上面的类型是
string
,太笼统了。 Not every string has an entry in the schedule object.并非每个字符串在时间表 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.您和我都知道,当您执行
diary.schedule[dayKey]
时,唯一可能访问的是"monday"
,但这在 typescript 正在使用的类型信息中不可用。
You have several options of more specific types.您有多个更具体类型的选项。 You could specify that it's one of the keys in Schedule:
您可以指定它是 Schedule 中的键之一:
const dayKey: keyof Schedule = 'monday';
Or you could specify that it's specifically "monday"
或者您可以指定它是专门的
"monday"
const dayKey: 'monday' = 'monday';
Another way to specify that it's specifically "monday"
is like this:另一种指定它是
"monday"
的方法是这样的:
const dayKey = 'monday' as const;
Prefer to use particular data-types.更喜欢使用特定的数据类型。 but in few cases, where you get dynamic response, you can declare like this:
但在少数情况下,当您获得动态响应时,您可以这样声明:
let obj = Array<any>()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.