Profile picture of Liam Moat

Liam Moat

Principal Software Engineer at Microsoft

Import JSON files with TypeScript

By Liam Moat. . 1 minutes read.

TypeScript 2.9, which was released in May 2018, introduced a new compiler option called resolveJsonModule. This allows you to import .json files and interpret the contents as a well-typed JavaScript Object - which means the compiler will recognise types like string, number and boolean.

Take the example below. This file is called config.json. It has two properties isProduction and logLevel with type boolean and string respectively.

{
    "isProduction": false,
    "logLevel": "info"
}

With resolveJsonModule enabled, you can import this file like any other module:

import * as config from './config.json';
config.isProduction === true; // Okay
config.logLevel === 2; // Error - Can't compare a `string` and `number`

By default, this feature is disabled. You can enable it in your project’s tsconfig.json file:

{
    "compilerOptions": {
        "module": "commonjs",
        "resolveJsonModule": true,
        "esModuleInterop": true,
        "outDir": "lib"
    },
    "include": ["src"]
}

Alternatively, you can enable it when running tsc:

tsc --resolveJsonModule

You can also selectively import individual properties from your .json file:

import {isProduction} from './config.json';
isProduction === true; // Okay

Take a look at TypeScript 2.9 announcement to see what other new features came with TypeScript 2.9.