microsoft / microsoft/TypeScript

import ConstJson from './config.json' as const;

未关闭
#32,063 112 条评论 1829 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

Awaiting More Feedback Suggestion
主要语言
Go
星标
111k
派生
14.3k
平均合并
2 天 4 小时
30 天内合并 PR
132

描述

Suggestion

The ability to get const types from a JSON configuration file.

If the json is:

{
  "appLocales": ["FR","BE"]
}

I want to import the JSON and get a {appLocales: "FR" | "BE"} type instead of string

As suggested here, this could rely on ES import attributes (stage 4, ES2025, TypeScript 5.3):

import data from "./data.json" with { type: "json", const: true };

Use Cases

The current approach gives a too broad type string. I understand it makes by default, but having the possibility to import a narrower type would be helpful: it would permit me to avoid maintaining both a runtime locale list + a union type that contains the values that are already in the list, ensuring my type and my runtime values are in sync.

It is possible to type a JSON file explicitly using allowArbitraryExtensions: true and a .d.json.ts file, but this doesn't permit to infer the type from the JSON directly, requires explicit typing and maintenance.

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Links:

This feature has been mentioned:

Search Terms

json const assertion import attributes with allowArbitraryExtensions

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先查看 issue 讨论、TypeScript 5.3 的 import-attributes 文档,以及现有的 allowArbitraryExtensions 方法。完成的标准是:使用提议的 const 属性的 JSON import 可以推断出诸如 "FR" | "BE" 这样的字面量值,同时不改变现有的 import 或生成的 JavaScript。

由索引模型根据 Issue 内容生成。

评估

技术栈
javascript, typescript
领域
compilers
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
冷清
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。