如何定义导入 json 的类型?例如
{
"things": "foo"
}
interface Data {
things: String,
another?: String
}
import data from './data.json' // Should have type Data
console.log(data.things)
console.log(data.another) // Should be allowed but undefined
resolveJsonModule
选项将自动为导入的 JSON 生成类型,但它不完整,因为 JSON 可能不包含数据的所有可能字段。我如何自己定义类型?
最佳答案
我可以在这里想到3种主要方式:
require
,如下所示:const data: Data = require('./data.json')
import
,但使用额外的变量(键入),如下所示:import untypedData from './data.json'
const data: Data = untypedData
typeRoots
的 tsconfig.json
部分,如下所示:// File data.d.ts
declare module "data.json" {
things: String,
another?: String
}
// File tsconfig.json
{
...
"typeRoots": [
"/*path to data.d.ts*/"
]
}
这将让您 import
以及正确输入导入的项目也可以看看
Importing json file in TypeScript
关于typescript - 将 JSON 作为类型导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65775338/