json - 在 typescript 中为 JSON 文件添加类型定义
问题描述
我有一个config.json
位于我的 typescript 项目中的配置文件,我想为其添加强类型。
src/config.json
{
"id": "some-id-string",
"data": {
"somekey" : "some value"
}
}
为了添加打字,我index.d.ts
也在我的项目中添加了一个文件:
src/index.d.ts
declare module 'config.json' {
export const id: string;
export const data: Record<string, string>;
}
但是它似乎不起作用,因为我可以将任意字段添加到我的 config.json 并且打字稿很乐意让它们通过,即:
src/config.json
{
"id": "some-id-string",
"foo": "bar", // <-- typescript doesn't catch this
"data": {
"somekey" : "some value"
}
}
我使用create-react-app
typescript 标志创建了这个项目,它产生以下内容tsconfig.json
:
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": ["src"]
}
我想我在这里遗漏了一些小步骤,但我不确定,我找不到很多如何做到这一点的例子。
编辑:
这似乎是可行的,因为它tsconfig.json
本身具有强类型:
解决方案
Typescript 不会验证您的 json。它仅适用于.ts
和.tsx
文件。
您d.ts
将要做的是假设从中导入的数据config.json
符合您的类型,但实际上并不能确保因为 json 文件在打字稿的域之外。
一种解决方法是将此配置放在一个config.ts
文件中,而不是使用以下内容:
// config.ts
export default {
//...
} as MyDataFormat
推荐阅读
- c# - 布尔变量保持统一重置
- orgchart - 关于 Balkan Graph Orgchart 中的垂直视图和水平视图
- git - 为什么`git checkout -m`没有合并就成功了?
- php - WooCommerce:添加自定义类以选择包装器
- java - 如何按日期对对象列表进行分组?
- java - 从 java 执行 python scipt 时找不到文件
- html - 随着浏览器窗口的增加,随时保持横幅响应
- python - pythonnet clr 在 jupyter 笔记本中无法识别
- python - 重新运行 model.fit 时使用阶跃衰减训练不保留最后一个 epoch。学习率错误
- ios - 我应该提交 ios/Runner.xcworkspace/xcshareddata/ 吗?