typescript - 如何修复隐式任何属性的数组访问
问题描述
我有这个代码:
function getKey(): string {
return 'foo';
}
function dummy(): void {
const object = {};
const key: string = getKey();
const value: any = 42;
object[key] = value; // ERROR: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
}
我知道存在错误,因为我启用了noImplicitAny
更清晰的代码,但是设置此属性的干净方法是什么?
解决方案
您可以声明一个Record
类型:
function getKey(): string {
return 'foo';
}
function dummy(): void {
const object: Record<string, any> = {}; // Here you can define the type of value, example string or number.
const key: string = getKey();
const value: any = 42;
object[key] = value; // Not error
}
推荐阅读
- python - 无法用scrapy提取分页链接
- git - Gitlab 项目的“活动日志”显示错误用户推送的分支
- java - 二进制转换器 Java
- java - 在快速排序中计算比较和交换
- python - Celery任务突然停止执行,节点找不到彼此
- r - R 3.5 安装 Manjaro
- python - 如何使用从一个数据中切割的十分位切割另一数据?
- java - 根据填充的editTexts数量打开另一个活动
- wpf - WPF 如何手动设置控件的 Validation.HasError 属性?
- android - 使我的应用程序崩溃,然后通过模拟器运行应用程序(API 23 Android 6.0)