【发布时间】:2019-08-29 22:02:10
【问题描述】:
我有以下包含配置的 json 文件:
{
"config1": { //this would be a map
"a": [ "string1", "string2"],
"b": [ "string1", "string2"]
}
}
在迁移到打字稿之前,以下工作:
import * as myConfig from './config.json';
...
myConfig.config1[this.state.section]; //section would be either "a" or "b"
现在代码给了我:
元素隐含地具有“任何”类型,因为 blablabla 没有索引签名
请注意,我确保在我的 tsconfig 文件中设置了以下内容:
"esModuleInterop": true,
"resolveJsonModule": true,
但它仍然不起作用。 我错过了什么?
编辑:
这似乎与运行时验证有关,以下似乎很好:
myConfig.config1["a"]; //alright!
但这不是:
const name:string = "a";
myConfig.config1[name]; //NOT!
不管我需要传递一个变量..我该怎么做? :(
【问题讨论】:
-
为了使括号符号在您的配置中起作用,请定义一个索引签名,如
interface IData { [ key: string ]: object; }您可以阅读更多关于它的信息typescriptlang.org/docs/handbook/…
标签: json reactjs typescript