我有这个代码:
\nconst expressionAttributeValues = {};\nexpressionAttributeValues[`:${status}`] = status; // TSLinst error\n// status is a string\nRun Code Online (Sandbox Code Playgroud)\n我收到了 TSlint 错误:
\n TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. \xc2\xa0\xc2\xa0No index signature with a parameter of type 'string' was found on type '{}'.\nRun Code Online (Sandbox Code Playgroud)\n这行有什么问题吗?
\n定义 时const expressionAttributeValues = {},您没有给出显式类型,因此编译器隐式假定您分配的值就是该类型。在本例中,您分配{}, so 一个空对象。就好像您会这样输入:const expressionAttributeValues: {} = {}。
现在,根据定义,没有属性的空对象没有键。
接下来,您尝试访问该对象的属性:${status}。由于编译器现在认为expressionAttributeValues只能是没有任何属性的对象,因此它会抱怨。
原始且不太优雅的解决方案是仅expressionAttributeValues键入any: const expressionAttributeValues: any = {}。这将停止编译器警告,因为现在expressionAttributeValues可以是任何东西,因此具有任何属性。
如果可能的话,更优雅的方法是更明确地键入expressionAttributeValuesand :${status}。
例如:
interface MyType {
a?: string;
b?: string;
c?: string;
}
const expressionAttributeValues: MyType = {};
const property: keyof MyType = 'a';
console.log(expressionAttributeValues[property]);
Run Code Online (Sandbox Code Playgroud)
最小定义(“所有键都是有效的,并且它们的属性值都是字符串”)也可以是:
type MyType {
[key: string]: string;
}
Run Code Online (Sandbox Code Playgroud)