在 TypeScript 中将 JSON 文件导入为 const

Leo*_*nor 7 arrays import json typescript

我想从数组元素的属性创建联合类型。如果数组是内联的,那么使用常量断言将非常简单。

const arr = [{ "name": "One" }, { "name": "Two" }] as const;

type name = typeof arr[number]["name"];
// name = "One" | "Two"
Run Code Online (Sandbox Code Playgroud)

请注意,没有as const类型name变为等于string,这不是意图。

我面临的问题是数组是在单独的 JSON 文件中定义的。我"resolveJsonModule": true在 TypeScript 选项中进行了设置,以便可以在我的模块中导入 JSON 文件。但是随后编译器扩大了数组中所有属性的类型,因为as const定义中没有。

import * as arr from "./array.json";

type name = typeof arr[number]["name"];
// name = string (!)
Run Code Online (Sandbox Code Playgroud)

有没有办法可以在不扩展类型的情况下导入 JSON 文件?

dx_*_*_dt 12

我也需要这个问题的答案,然后意识到,“嘿,这不是一个很难编写的 npm 包。”

我不相信有一种纯粹的 TS 方法可以做到这一点。我创建的包名为ts-json-as-const.

npm install -D ts-json-as-const
npx ts-json-as-const ./path/to/file.json ./path/to/second/file.json
Run Code Online (Sandbox Code Playgroud)
JSON 文件示例 ( example.json)
{
  "foo": {
    "bar": false,
    "baz": true,
    "i-can": "hascheezburger"
  },
  "array": [ 1, 2, 3, { "foo": 1, "bar": [ 4, 5 ] }, 6 ]
}
Run Code Online (Sandbox Code Playgroud)
输出example.json.d.ts
interface Example {
  foo: {
    bar: false;
    baz: true;
    'i-can': 'hascheezburger';
  },
  array: [
    1,
    2,
    3,
    {
      foo: 1;
      bar: [
        4,
        5
      ]
    },
    6
  ]
}

declare const Example: Example;

export = Example;
Run Code Online (Sandbox Code Playgroud)

我承认,数组间距不是很大,但是谁会查看 .d.ts 文件中的 json 文件呢?


小智 -6

https://hackernoon.com/import-json-into-typescript-8d465beded79

示例.json:

{
    "name": "testing"
}
Run Code Online (Sandbox Code Playgroud)

javascript:

// ES6/ES2015
// app.js

import * as data from './example.json';

const word = data.name;

console.log(word); // output 'testing'
Run Code Online (Sandbox Code Playgroud)

或者在 Typescript 中,相同的代码会抛出错误:

找不到模块“example.json”

[更新]解决方案:Typescript 2.9 支持 JSON 导入!

{
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true  
  }
}
Run Code Online (Sandbox Code Playgroud)