用“字符串枚举”转换JSON属性到接口

发布于 2025-02-04 09:20:13 字数 1296 浏览 1 评论 0原文

在我们的项目中,我们使用从BE到客户端的数据。现在问题是,当我们模拟数据时,它包含模拟JSON文件中的“枚举字符串”。

然后将这些模拟JSON文件导入这样的导入:import testjson从'.test.json';('ResolveJsonModule'在TSCONFIG中启用了),该''resolvejsonmodule'在Tsconfig中启用),它基于静态JSON形状为它们提供了一种类型'。 ' (请参阅:

现在,该枚举属性生成的类型是字符串而不是枚举,因此,当我尝试将JSON投射到接口类型时,它会给我带来错误:类型'String''无法分配给类型'testEnum' 。

const testJSON = {
  name: 'hello World',
  enumProp: "MYTESTENUM_2",
};

enum testEnum {
  MYTESTENUM = "MYTESTENUM",
  MYTESTENUM_2 = "MYTESTENUM_2",
}

interface testinterface {
  name: string;
  enumProp: testEnum;
}

//const castJsonFile: testinterface = testJSON; // not compiling because the "string enums" cannot be converted
const castJsonFile: testinterface = testJSON as any;  // any cast is needed, to get it compiling, but looses all type safety


// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = (castJsonFile.enumProp === testEnum.MYTESTENUM_2) as any as string;

​edit/typecript-fjy8zs?file = index.ts

如果我不使用“字符串枚举”,它将正常工作,但这是一个无法完成的更改。

有没有办法告诉Typescript如果在JSON文件中找到这样的属性,则可以将“字符串枚举”视为枚举?

In our project, we are using string enum, to send the data from the BE to the client. Now the issue is, that when we mock the data, it contains the "enum strings" in the mock json files.

These mock json files are then imported like this: import testJson from '.test.json'; ('resolveJsonModule' is enabled in tsconfig), which gives them a type 'based on the static JSON shape.' (See: Resolve JSON Module).

Now the type which is generated for that enum property is string and not enum, so when I try to cast the json to the interface type, it throws me an error: Type 'string' is not assignable to type 'testEnum'.

Stackblitz example:

const testJSON = {
  name: 'hello World',
  enumProp: "MYTESTENUM_2",
};

enum testEnum {
  MYTESTENUM = "MYTESTENUM",
  MYTESTENUM_2 = "MYTESTENUM_2",
}

interface testinterface {
  name: string;
  enumProp: testEnum;
}

//const castJsonFile: testinterface = testJSON; // not compiling because the "string enums" cannot be converted
const castJsonFile: testinterface = testJSON as any;  // any cast is needed, to get it compiling, but looses all type safety


// Write TypeScript code!
const appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = (castJsonFile.enumProp === testEnum.MYTESTENUM_2) as any as string;

Link: https://stackblitz.com/edit/typescript-fjy8zs?file=index.ts

If I would not use "string enums" it would work fine, but this is a change which cannot be done.

Is there a way to tell typescript to treat the "string enums" as enums if he finds such a property in a JSON file?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文