reactjs - Using keyof in Typescript to get rid of 'element implicitly has any type' error
问题描述
I know this has other questions on it but none of them seem to be helping me understand what I need to do to fix this.
I have an attribute that I have set as part of my Component's state, and this object is supposed to be an object that I'm using as a "map" to store key-value pairs.
SampleAttribute: {
x: '',
y: []
}
The value for it is set in one of my component's functions, where I use this.setState to set the attribute to an object I initialized as follows:
let kvPairs: { [key: string]: any[] } = {};
However, at some point before my function calls this.setState, it stores this.state.SampleAttribute in a variable sampleAttribute
. At this point, I want to check if a string array listOfThings
has any of its elements as a key of sampleAttribute, so I am calling
listOfThings.map(thing => {
if (sampleAttribute[thing])
// do stuff
})
It is at the line in the if statement that I get the error:
TypeScript: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
I understand many of the answers require using keyof to let the compiler know what it can accept as strings to index the object, but it seems doing that requires me creating a new type, since keyof requires a Type passed to it...so I'm just confused as to how I can do this without going that route.
解决方案
你可以像这样创建一个类型安全的访问器:
const doOnIndex = <T>(obj: T, thing: string, fn: (ele: typeof obj[keyof typeof obj]) => void): void => {
if (thing in obj) {
fn(obj[thing]);
}
};
// Used like
doOnIndex(SampleAttribute, thing, ele => ele);
在这种情况下,您告诉编译器,因为您成功索引了对象,结果类型必须是已知对象的值类型的并集。
我不确定为什么 kvPairs 是相关的,使用完整的代码示例会更容易理解。
推荐阅读
- python - 有人可以帮我矢量化这个 for 循环吗?
- ios - xcode iOS 缩小文字放大镜
- javascript - 当我使用状态图中的数据时崩溃
- javascript - 如何在 HTML/CSS 中居中超大图像,同时允许向左/向右/向上/向下滚动
- docker - Docker jupyter 500:内部服务器错误/未知导出器“ipynb”
- php - 如何在不更改 html 文件中的路径的情况下显示图片?
- javascript - 滚动和位置问题:已修复
- wordpress - 将 woocommerce 产品图片重定向到自定义 URL 而不是产品页面
- android - 如何使用 UcanAccess 将 accdb 连接到 Android 应用程序?
- postgresql - 为什么在 ORDER BY 中“输出列名必须独立,即不能在表达式中使用”?