首页 > 解决方案 > 在 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-apptypescript 标志创建了这个项目,它产生以下内容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本身具有强类型:

强类型json

标签: jsontypescriptvisual-studio-code

解决方案


Typescript 不会验证您的 json。它仅适用于.ts.tsx文件。

d.ts将要做的是假设从中导入的数据config.json符合您的类型,但实际上并不能确保因为 json 文件在打字稿的域之外。

一种解决方法是将此配置放在一个config.ts文件中,而不是使用以下内容:

// config.ts
export default {
  //...
} as MyDataFormat

推荐阅读