gpt4 book ai didi

typescript TS7053 : Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'

转载 作者:行者123 更新时间:2023-12-05 08:49:36 26 4
gpt4 key购买 nike

我有这个代码:

const expressionAttributeValues = {};
expressionAttributeValues[`:${status}`] = status; // TSLinst error
// status is a string

我得到了 TSlint 错误:

 TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.   No index signature with a parameter of type 'string' was found on type '{}'.

那一行有什么问题?

最佳答案

在定义 const expressionAttributeValues = {} 时,您没有给出显式类型,因此编译器隐式假定您分配的值就是该类型。在这种情况下,您分配 {},因此是一个空对象。就好像您会这样输入:const expressionAttributeValues: {} = {}

根据定义,现在没有属性的空对象没有键。

接下来,您尝试访问对象的属性 :${status}。由于编译器现在认为 expressionAttributeValues 可以是一个没有任何属性的对象,它会提示。

原始且不太优雅的解决方案是将 expressionAttributeValues 键入 any:const expressionAttributeValues: any = {}。这将停止编译器警告,因为现在 expressionAttributeValues 可以是任何东西,因此具有任何属性。

如果可能的话,更优雅的方法是更明确地键入 expressionAttributeValues:${status}

例如:

interface MyType {
a?: string;
b?: string;
c?: string;
}
const expressionAttributeValues: MyType = {};
const property: keyof MyType = 'a';
console.log(expressionAttributeValues[property]);

最小定义(“所有键都是有效的,并且它们的属性值都是字符串”)也可以是:

type MyType {
[key: string]: string;
}

关于 typescript TS7053 : Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63676021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com