Skip to content

Allow checking json in conjunction with .d.json.ts filesΒ #52994

@Jamesernator

Description

@Jamesernator

Suggestion

πŸ” Search Terms

checkJson, check json, .d.json.ts

βœ… Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

So in TS 5.0 we can add .d.json.ts files to type JSON files, i.e.:

// config.d.json.ts

declare const config: {
    option?: string,
    option2?: number,
};

export default config;
// config.json
{
    "option": "foo",
    "option2": 12
}
// main.ts
import config from "./config.json" assert { type: "json" };

// config has type { option?: string, option2?: number }

This is nice, but it would be better if we could validate that the corresponding .json files do in fact actually match the type. I'd like to propose a new option, checkJson that when set validates types errors within JSON files.

For example suppose we have:

// config.d.json.ts
declare const config: {
    value: string,
};

export default config;
// config.json
{
    "value": 3
}

Then TypeScript would report a type error when running tsc on the project (or in the editor).

πŸ“ƒ Motivating Example

Pretty much anywhere manual JSON files are used in conjunction with .d.json.ts files would be useful. The point of TS is to help detect errors, extending this to JSON is a natural extension.

In particular this would make a particularly good alternative to JSON schema support as I proposed in another issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions