【TypeScript】Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'
前言
在 TypeScript
中为对象属性赋值报错,截图如下。
const env = {}
env['a'] = 1
分析
对象 env
,其属性名具有 any
类型,故表达式 a
不能用于索引类型 {}
。需要约束属性名类型。
解决
const env: Record<string, any> = {}
env['a'] = 1
约束对象类型,告诉编译器对象 env
的参数将是字符串/值(字符串/任意)对的集合。
参考
element-implicitly-has-an-any-type-because-expression-of-type-string-cant-b