我有此代码:
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 '{}'.
那一行怎么了?
答案 0 :(得分:1)
由于您使用空对象初始化了常量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
答案 1 :(得分:1)
在定义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;
}
答案 2 :(得分:0)
您需要向编译器提示expressionAttributeValues
的类型是从string
到string
的键值映射,即
const expressionAttributeValues: { [key: string]: string } = {};