LoginSignup
76
54

More than 3 years have passed since last update.

TypeScriptでJSONファイルを型付きで読み込む

Last updated at Posted at 2018-02-20

こんな感じのjsonファイルを読み込みたい。

dummy.json
{
  "foo": "foo",
  "bar": 123
}

自動で型定義

typescript@^2.9.1(2018.5.31~)からはtsconfig.jsonresolveJsonModulemoduleResolutionを設定すれば型の付いたJSONを直接インポートできるようになりました。

tsconfig.json
{
  "compilerOptions": {
    "moduleResolution": "node",
    "resolveJsonModule": true
  }
}
import dummy from './dummy.json'

console.log(dummy.foo); 

自分で型定義

型を付けるための*.d.tsを作ります。名前はtypes/json/index.d.tsにしました。(なんでもいい)
そして中身はこんな感じにします。

types/json/index.d.ts
declare module '*/test-data.json' {
  interface TestData {
    foo: string;
    bar: number;
  }

  const value: TestData;
  export = value;
}

*/data-test.jsonとしてるのは./data-test.json../data-test.jsonみたいなimportにもマッチさせるためです。

後は、これを読み込むだけ。

import dataTest = require('./data-test.json');

別にanyで構わないならvalue: Fooとしてる部分をvalue: anyにすればOKです。

76
54
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
76
54