简体   繁体   English

从 JSON object 创建 typescript 接口

[英]Creating typescript interface from JSON object

Is there a way to import a JSON object into a Typescript program so that it is automatically strongly typed and constant?有没有办法将 JSON object 导入到 Typescript 程序中,使其自动成为强类型和常量?

So if I have this code in person.json :所以如果我有这个代码person.json

{
  "name": "Steven",
  "eyeColor": "brown"
}

I want to be able to import it to a Typescript program as such:我希望能够将它导入到 Typescript 程序中:

// personTest.ts
const person = require('person.json');
console.log(person.name); // This should be fine
console.log(person.age);  // This should cause a compile-time error, because this property is not defined

add this on tsconfig.json将其添加到 tsconfig.json

{

   ... //prev code

   "resolveJsonModule": true, 

}

then you can use ESM modules to import json file and it will be auto typed the object values然后您可以使用 ESM 模块导入 json 文件,它将自动输入 object 值

import person from './person.json' //be sure from the json path

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM