【发布时间】:2020-06-03 03:49:28
【问题描述】:
我有一些符合我定义的 TypeScript 接口的 JSON 文件。
在大多数情况下,当导入此类 JSON 文件并将它们分配给类型化变量时,TypeScript 能够自动推断类型签名(参见下面代码中的 behaves exactly as I want)。但是,当类型包含 字符串枚举 时,它不再起作用(请参阅 DOES NOT behave)。
以下是工作中的Minimal, Reproducible Example:
valid.json
{ "id": 3.14159 }
invalid.json
{ "id": "3.14159" }
validEnum.json
{ "color": "red" }
invalidEnum.json
{ "color": "chartreuse" }
index.ts
import validJson from './valid.json'
import invalidJson from './invalid.json'
import validJsonEnum from './validEnum.json'
import invalidJsonEnum from './invalidEnum.json'
type ColorType = 'red' | 'blue' | 'yellow'
type IJsonType = {"id": number}
type IJsonTypeWithEnum = {"color": ColorType}
// behaves exactly as I want
const a: IJsonType = validJson // no error
const b: IJsonType = invalidJson // ERROR: Type 'string' is not assignable to type 'number'.
// DOES NOT behave as I want: SHOULD NOT error
const c: IJsonTypeWithEnum = validJsonEnum // ERROR: Type 'string' is not assignable to type 'ColorType'.
// DOES NOT behave as I want: error should be that "chartreuse" is not assignable to type 'ColorType'
const d: IJsonTypeWithEnum = invalidJsonEnum // ERROR: Type 'string' is not assignable to type 'ColorType'.
我可以使用type IJsonTypeWithEnum = {"color": string} 使错误消失,但这违背了目的。
是否有任何变通方法或编译器开关可以让 TypeScript 将 JSON 中的枚举值识别为字符串?还是 JSON 类型推断的 TypeScript 限制?
【问题讨论】:
-
如果你没有找到更好的选择 - 看看
io-ts。 -
如果您遵循How to create a Minimal, Reproducible Example 的 SO guildines,这个问题可以变得更容易理解和解决。我会尽快提交修改建议。
-
所以我提交的编辑中的 MRE 重现了您的错误消息,但我无法让肯定的情况起作用(“TypeScript 能够自动推断类型签名”)。您能否接受我的编辑,然后添加代码以显示不涉及枚举字符串时它是如何工作的?现在您可以看到 MRE 对这个问题的重要性。一旦获得可靠的 MRE,我会支持这个问题。
-
@Inigo 我已经检查了您的编辑。感谢您的效果,但它不正确。允许在最新版本的 TS 中导入
.json文件,它将被转换为类型良好的对象。您的 MRE 的字符串模板应替换为对象文字以反映事实。仅供参考,我会改进您的编辑并应用它。 -
@Inigo 错误消息只是表面上相同,但原因完全不同。您对另一个答案
Conversion of type 'string' to type 'IJsonType' may be a mistake发表评论,这是因为最初您使用字符串模板将jsonData声明为字符串,如果您从.json文件中导入它,则情况并非如此。
标签: json typescript enums