TypeScript TS7053:元素隐式具有 'any' 类型,因为 'string' 类型的表达式不能用于索引类型“{}”

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

我有这个代码:

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 expressionAttibuteValues 并且没有为该 const 提供类型,因此 TS 编译器自动假定 expressionAttributeValues 是空对象类型。这就是为什么它抱怨从其中访问 属性 。添加类型或 anyexpressionAttributeValues

你需要提示编译器 expressionAttributeValues 的类型是从 stringstring 的键值映射,即

const expressionAttributeValues: { [key: string]: string } = {};

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

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

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

原始的 not-so-elegant 解决方案是将 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;
}