I have a JSON file that looks like following:

{

  "primaryBright":    "#2DC6FB",
  "primaryMain":      "#05B4F0",
  "primaryDarker":    "#04A1D7",
  "primaryDarkest":   "#048FBE",

  "secondaryBright":  "#4CD2C0",
  "secondaryMain":    "#00BFA5",
  "secondaryDarker":  "#009884",
  "secondaryDarkest": "#007F6E",

  "tertiaryMain":     "#FA555A",
  "tertiaryDarker":   "#F93C42",
  "tertiaryDarkest":  "#F9232A",

  "darkGrey":         "#333333",
  "lightGrey":        "#777777"
}

我正试图把它导入一个.tsx文件.为此,我在类型定义中添加了以下内容:

declare module "*.json" {
  const value: any;
  export default value;
}

And I'm importing it like this.

import colors = require('../colors.json')

And in the file, I use the color primaryMain as colors.primaryMain. However I get an error:

"*.json"的类型"typeOf"上不存在属性"PrimiyMain"

推荐答案

The import form 和 the module declaration need to agree about the shape of the module, about what it exports.

When you write (a suboptimal practice for importing JSON since TypeScript 2.9 when targeting compatible module formatssee note)

declare module "*.json" {
  const value: any;
  export default value;
}

您的意思是,所有具有以.json结尾的说明符的模块都有一个导出named default.

There are several ways you can correctly consume such a module including

import a from "a.json";
a.primaryMain

import * as a from "a.json";
a.default.primaryMain

import {default as a} from "a.json";
a.primaryMain

import a = require("a.json");
a.default.primaryMain

The first form is the best 和 the syntactic sugar it leverages is the very reason JavaScript has default exports.

However I mentioned the other forms to give you a hint about what's going wrong. Pay special attention to the last one. require gives you an object representing the module itself 和 not its exported bindings.

So why the error? Because you wrote

import a = require("a.json");
a.primaryMain

然而,你们的"*.json"并没有申报名为primaryMain的出口.

All of this assumes that your module loader is providing the JSON as the default export as suggested by your original declaration.

Note: Since TypeScript 2.9, you can use the --resolveJsonModule compiler flag to have TypeScript analyze imported .json files 和 provide correct information regarding their shape obviating the need for a wildcard module declaration 和 validating the presence of the file. This is not supported for certain target module formats.

Json相关问答推荐

使用单元和非单元版本反序列化Rust中的枚举,而无需编写自定义反序列化程序

Allof Indide的JSON模式之一

在Vega中如何通过滑块改变条形图的宽度

将 std::可选值存储到 json 文件 C++

Golang jsonrpc2 服务器在哪里监听?

条件性构建/修改嵌套对象数组

在 NX 工作区中跨多个应用共享 ngx-translate 翻译文件

使用 jq 和 awk 拆分大型 JSON 文件

如果有 1 个元素,如何防止 ConvertFrom-Json 折叠嵌套数组

如何使用 boost::json::value 调用无参数函数

如何比较 JSON 文档并返回与 Jackson 或 Gson 的差异?

避免 KeyError 的默认字典键

将 PHP 结果数组转换为 JSON

Jackson 没有使用 @JsonProperty 覆盖 Getter

Golang struct 的 XML 和 JSON 标签?

python追加到json对象中的数组

如何使用 SwiftyJSON 遍历 JSON?

Laravel 5 控制器将 JSON 整数作为字符串发送

如何从 jQuery ajax 调用将复杂对象传递给 ASP.NET WebApi GET?

log4j 支持 JSON 格式吗?