How do I use the type of imported JSON file in TypeScript

Viewed 444

I have a project built with NextJS, React, GraphQL and TypeScript. In this project, I have some static JSON data stored in ../data/applications.json:

[
    {
        "id": "elector-v3",
        "name": "Tesla Auto Pilot Elector API",
        "apiName": "tap-api-v3-elector",
        "apiPath": "/tap/v3/elector"
    },
    {
        "id": "clairvoyance-v2",
        "name": "Tesla Auto Pilot Clairvoyance API",
        "apiName": "tap-api-v2-clairvoyance",
        "apiPath": "/tap/v2/clairvoyance"
    },
    ... and many more...
]

With NextJS and TypeScript, I can import this data directly in my TS file:

import applicationsData from "../data/applications.json"

I notice when handling this data, TypeScript recognizes the shape of this data.

How can I create a type out of this data?

1 Answers

Assuming that each object in your array has the same four properties, then typeof applicationsData[0] will get you the appropriate type. You can then use a Type Alias to create a proper name for this type:

type ApplicationData = typeof applicationsData[0]

Remember: using the inferred type will work for basic use cases like this, where you control the data and its structure is stable. You're basically using the first element as a "sample" for all the data within your array. For cases where the structure is more volatile it's better to define your own type definition by hand.

Related