首页 > 解决方案 > 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.

标签: reactjstypescript

解决方案


你可以像这样创建一个类型安全的访问器:

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 是相关的,使用完整的代码示例会容易理解。


推荐阅读