All Articles

Override the Type of a JSON File

Matt Pocock
Matt PocockMatt is a well-regarded TypeScript expert known for his ability to demystify complex TypeScript concepts.

Need to manually type a JSON file?

I learned today that you can add a .d.json.ts file to manually assign a type to a JSON import.

For example, if you have a data.json file, you can create a data.d.json.ts file and define the type inside:

// data.d.json.ts
declare const data: Record<string, string>;

export default data;

You can change the Record<string, string> type to match the desired shape.

To make TypeScript recognize .d.json.ts files, you need to add a setting in your tsconfig.json:

json
{
"compilerOptions": {
"allowArbitraryExtensions": true
}
}

This setting lets TypeScript use .d.json.ts files.

Why Would You Do This?

This technique can be particularly useful when working with large .json files used for test fixtures. If TypeScript infers the type of all the data in the file, it can significantly slow down the TypeScript transpilation process - and your IDE.

By assigning a broader type like Record<string, string>, TypeScript will use the specified type instead. This optimization can greatly improve the performance of your TypeScript transpilation.

Matt's signature

Share this article with your friends

`any` Considered Harmful, Except For These Cases

Discover when it's appropriate to use TypeScript's any type despite its risks. Learn about legitimate cases where any is necessary.

Matt Pocock
Matt Pocock

No, TypeScript Types Don't Exist At Runtime

Learn why TypeScript's types don't exist at runtime. Discover how TypeScript compiles down to JavaScript and how it differs from other strongly-typed languages.

Matt Pocock
Matt Pocock

Deriving vs Decoupling: When NOT To Be A TypeScript Wizard

In this book teaser, we discuss deriving vs decoupling your types: when building relationships between your types or segregating them makes sense.

Matt Pocock
Matt Pocock

NoInfer: TypeScript 5.4's New Utility Type

Learn how TypeScript's new utility type, NoInfer, can improve inference behavior by controlling where types are inferred in generic functions.

Matt Pocock
Matt Pocock