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

问题描述

我有此代码:

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 '{}'.

那一行怎么了?

解决方法

由于您使用空对象初始化了常量dat %>% arrange(Region) %>% group_by(Tree,Fertilized) %>% summarize(fold_change = Fruits[2] / Fruits[1]) #> `summarise()` regrouping output by 'Tree' (override with `.groups` argument) #> # A tibble: 4 x 3 #> # Groups: Tree [2] #> Tree Fertilized fold_change #> <chr> <chr> <dbl> #> 1 apple " heavily" 1.5 #> 2 apple " lightly" 2 #> 3 pear " heavily" 2 #> 4 pear " lightly" 0.75 ,并且没有为该常量提供类型,因此TS编译器会自动假定expressionAttibuteValues的类型为空对象。这就是为什么它抱怨从内部访问属性。将类型或expressionAttributeValues添加到any

,

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

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

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

原始且不太优雅的解决方案是仅将expressionAttributeValues键入为anyconst 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;
}
,

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...