LoginSignup
27
17

More than 5 years have passed since last update.

resolveJsonModuleのtypeofメモ

Posted at

タイトルのまま、TypeScript 2.9にて追加されたresolveJsonModuleについてのメモ。
tsconfig.jsonの設定を変更することにより、jsonファイルから型解決した状態で値を取得でき、わざわざjson用のinterfaceを作成しなくてもよくなった。

Angular公式のHttpClientのJSONデータを取得するを例にあげると、jsonファイルさえあれば、interfaceはtypeofすることでまかなえる。

config.json
{
  "heroesUrl": "api/heroes",
  "textfile": "assets/textfile.txt"
}
config/config.service.ts
// export interface Config {
//   heroesUrl: string;
//   textfile: string;
// }
export type Config = typeof import('../../assets/config.json');

もちろん、分けて書くこともできる。

分けて書く
import config from '../../assets/config.json';
export type Config = typeof config;

話は前後するが、angular/cliで作成したプロジェクトであれば、プロジェクト直下にあるtsconfig.jsonのcompilerOptionsに下記内容を追加することによって利用できるようになる。

/tsconfig.json(抜粋)
{
・・・
  "compilerOptions": {
・・・
    "resolveJsonModule": true,
    "esModuleInterop": true
  }
}
27
17
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
27
17