[英]Element implicitly has an 'any' type because expression of type 'string | number' can't be used to index type
I am getting the error:我收到错误消息:
Element implicitly has an 'any' type because expression of type 'string | number'
can't be used to index type 'IStorage'.
No index signature with a parameter of type 'string' was found on type 'IStorage'.
I see this issue in other posts but it doesn't make sense to my case.我在其他帖子中看到了这个问题,但这对我的情况没有意义。 I have this interface below:
我在下面有这个界面:
interface IStorage {
id: number
name: string
vendor_id: string
start_date: Date | null
end_date: Date | null
app: string
}
and this function:这个功能:
handleSetStorageValues = (index: number) => (event: {
name: string | number
value: string | number
}) => {
const storage = [...this.state.storage]
storage[index][event.name] = event.value // --> error here at [event.name]
this.setState(
prevState => {
return {
...prevState,
storage,
}
}
)
}
How do I specify the index signature type for this?如何为此指定索引签名类型?
event.name
is referring to the name property that I am also getting from the name
attribute on the input. event.name
指的是我也从输入的name
属性中获得的 name 属性。 Thank you!谢谢!
The proper type for a key that's gonna be used to access IStorage
is keyof IStorage
.用于访问
IStorage
的密钥的正确类型是keyof IStorage
。
You may change the type for event.name
to keyof IStorage
.您可以将 event.name 的类型更改为
event.name
keyof IStorage
。 Something like this:像这样的东西:
event: {
name: keyof IStorage
value: string | number
}
This will fix the read error, but you won't be able to write (assign) values.这将修复读取错误,但您将无法写入(分配)值。
You may think that you want to change the type for event.value
.您可能认为要更改
event.value
的类型。 Something like this:像这样的东西:
event: {
name: keyof IStorage
value: IStorage[keyof IStorage]
}
This won't work either, as now you do not match a name
with a value
so TS will complain as some combinations are not allowed.这也不起作用,因为现在您没有将
name
与value
匹配,因此 TS 会抱怨某些组合是不允许的。
Most likely you'll end up casting to any
and taking the heat for the type checking.最有可能的是,您最终会铸造到
any
类型并为类型检查付出代价。
(storage[index] as any)[event.name] = event.value
Probably the only type safe way of doing this is do manual checks for each property that can be a key of IStorage
and the same for each value.这样做的唯一类型安全方法可能是手动检查每个属性,这些属性可以是
IStorage
的键并且每个值都相同。 This will become increasingly difficult as IStorage
changes.随着
IStorage
的变化,这将变得越来越困难。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.