如何将一个枚举映射到打字稿中的另一个枚举?

编程入门 行业动态 更新时间:2024-10-09 07:27:35
本文介绍了如何将一个枚举映射到打字稿中的另一个枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想将一个具有枚举类型的对象的属性映射到另一个枚举类型的另一个对象的属性。

I want to map one object's property that has an enum type to another object's property that is other enum type.

我尝试使用将type1.a用作Enum2 或 Enum2 [type1.a] 没有成功。

I've tried with type1.a as Enum2 or Enum2[type1.a] with no success.

这是我的简化代码问题:

Here is my simplified code problem:

enum Enum1 { N = 0, A = 1, B = 2 } enum Enum2 { A = 1, B = 2 } interface Type1 { a: Enum1; } interface Type2 { a: Enum2; } const type1: Type1 = { a: Enum1.A }; const type2: Type2 = { a: type1.a };

尝试一下

抛出错误:

Type 'Enum1' is not assignable to type 'Enum2'. (property) Type2.a: Enum2

推荐答案

您需要将 type1.a 道具投射到 Enum2 。为此,您需要使用类型防护。

You need to cast the type1.a prop to Enum2. To do this you need to use a "Type Guard".

以下是您的代码示例:

enum Enum1 { N = 0, A = 1, B = 2 } enum Enum2 { A = 1, B = 2 } interface Type1 { a: Enum1; } interface Type2 { a: Enum2; } const type1: Type1 = { a: Enum1.N }; function isEnum2(value: any): value is Enum2 { let isEnum2 = false; for (let key in Enum2) { if (Enum2[key] === value) { isEnum2 = true; } } return isEnum2; } if (isEnum2(type1.a)) { const type2: Type2 = { a: type1.a }; }

尝试一下

当<$ c $在 if 块中使用c> isEnum2 函数,使道具 type1.a 变为如果只是块,则在该中键入 Enum2 。

When the isEnum2 function is used in the if block the prop type1.a becomes of type Enum2 inside that if block only.

注意:如果您愿意,可以使用 for..in 循环替换 isEnum2 中的内容正在使用ES2017或更高版本,并使用 Object.values :

Note: you could replace the content in the isEnum2 using for..in loop if you are using ES2017 or higher using Object.values:

return Object.values(Enum2).indexOf(value) > -1;

尝试一下(不适用于www.typescriptlang)

try it (Doesn't work in www.typescriptlang)

有关类型防护的详细信息

更多推荐

如何将一个枚举映射到打字稿中的另一个枚举?

本文发布于:2023-11-25 21:07:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631350.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!