简体   繁体   English

如何在打字稿中将联合类型转换为枚举?

[英]How to convert union type to enum in typescript?

I want to covert union type to enum or like enum in typescript我想将联合类型转换为 enum 或像打字稿中的 enum

It doesn't work out with my brain.这对我的大脑不起作用。

Thank you for reading my question.感谢您阅读我的问题。

type status = 'start' | 'loading' | 'stop';

class Loading {
    static staticStatus: status;
}
Loading.staticStatus.start; // i want to use.

or或者

type status = 'start' | 'loading' | 'stop';

enum statusEnum = ?????;

class Loading {
    static staticStatus = statusEnum;
}
Loading.staticStatus.start; // i want to use.

I'm sorry I didn't write my questions in detail.很抱歉我没有详细写下我的问题。

const schema ={
 status: Joi.string()
        .required()
        .valid(
            'start',
            'loading',
            'stop',
        )
}

// type setStatusType =  'start' | 'loading' | 'stop' is like this
type setStatusType = PickType<Joi.extractType<typeof schema>, 'status'>; 

enum statusEnum = ?????;

class Loading {
    static staticStatus = statusEnum;

    public setLoading() {
    this.status = Loading.staticStatus.loading // I want to use this.
    }
}

so I want to covert union type to enum...所以我想将联合类型转换为枚举......

Not sure how you would get an enum from a Union but you can easily do the reverse if you need both.不确定如何从Union获得enum ,但如果两者都需要,则可以轻松地进行相反的操作。

enum Status {
 start,
 loading,
 stop
}

type StatusAsUnion = keyof typeof Status

Hopefully this was useful希望这是有用的

Enums are defined with the enum keyword like this:枚举使用enum关键字定义,如下所示:

writing-readable-code-with-typescript-enums 用打字稿枚举编写可读代码

enum Continents {
    North_America,
    South_America,
    Africa,
    Asia,
    Europe,
    Antartica,
    Australia
}

// usage
var region = Continents.Africa;

Types of TypeScript enums TypeScript enums类型

There are three types of TypeScript enums namely: TypeScript 枚举共有三种类型,即:

  1. Numeric enums数字枚举
  2. String enums字符串枚举
  3. Heterogenous enums异构枚举

Numeric enums By default, TypeScript enums are number based.数字枚举默认情况下,TypeScript 枚举是基于数字的。 This means that they can store string values as numbers.这意味着它们可以将字符串值存储为数字。 Numbers and any other type that is compatible with it can be assigned to an instance of the enum.数字和与其兼容的任何其他类型都可以分配给枚举的实例。 Let's say we want to store days in the weekend.假设我们想在周末存储几天。 The representing enum in TypeScript can look something like this: TypeScript 中的表示枚举看起来像这样:

enum Weekend {
  Friday,
  Saturday,
  Sunday
}

In the code block above, we have an enum we call Weekend.在上面的代码块中,我们有一个名为 Weekend 的枚举。 The enum has three values namely: Friday, Saturday and Sunday.枚举具有三个值,即:星期五、星期六和星期日。 In TypeScript, just like in some other languages, enum values start from zero and increase by one for each member.在 TypeScript 中,就像在其他一些语言中一样,枚举值从零开始,并为每个成员增加一。 They will be stored like this:它们将像这样存储:

Friday = 0
Saturday = 1
Sunday = 2

We see that enums are always assigned numbers for storage, the value always takes the numeric value of zero, although we can customize the storage values with our own logic.我们看到枚举总是被分配数字进行存储,值总是取零的数值,尽管我们可以用我们自己的逻辑自定义存储值。

Custom numeric enums In TypeScript, we are allowed to dictate the first numeric value of our enumerations.自定义数字枚举在 TypeScript 中,我们可以指定枚举的第一个数字值。 Using the weekend days example above, we can initialize the first numeric value like this:使用上面的周末示例,我们可以像这样初始化第一个数值:

enum Weekend {
  Friday = 1,
  Saturday,
  Sunday
}

The above code block will store Friday as 1, Saturday as 2 and Sundayas 3. If we add a number to the first member, we still get sequential incrementation by one for the rest of the members.上面的代码块将星期五存储为 1,星期六存储为 2,星期日存储为 3。如果我们向第一个成员添加一个数字,我们仍然会为其余成员连续递增 1。 However, we have the power to dictate that we do not want a sequential trail by giving them any numerical value.但是,我们有权通过给它们任何数值来规定我们不想要顺序跟踪。 The code block below is semantic and works in TypeScript:下面的代码块是语义化的,适用于 TypeScript:

enum Weekend {
  Friday = 1,
  Saturday = 13,
  Sunday = 5
}

Just like other data types in TypeScript, we can use enums as function parameters or return types, like this:就像 TypeScript 中的其他数据类型一样,我们可以使用枚举作为函数参数或返回类型,如下所示:

Front-end Application Monitoring Identify Fix TrackGet a Free Trial >前端应用程序监控识别修复跟踪获取免费试用版 >

enum Weekend {
  Friday = 1,
  Saturday,
  Sunday
}

function getDate(Day: string): Weekend {
    if ( Day === 'TGIF') {
        return Weekend.Friday;
    }
 }

let DayType: Weekend = getDate('TGIF');

In the code block above, we declared a Weekend enum.在上面的代码块中,我们声明了一个 Weekend 枚举。 We then declared a getDate function that takes the input Day that returns a Weekend enum.然后我们声明了一个 getDate 函数,它接受返回 Weekend 枚举的输入 Day。 In the function, we check for some condition that now returns an enum member.在函数中,我们检查现在返回枚举成员的某些条件。

String enums So far we have only looked at enums where the member values are numbers.字符串枚举到目前为止,我们只研究了成员值为数字的枚举。 In TypeScript, your enum members can also be string values.在 TypeScript 中,您的枚举成员也可以是字符串值。 String enums are vital and easy to deal with for the purpose of readability during error logging and debugging because of their meaningful string values.为了在错误记录和调试期间的可读性,字符串枚举至关重要且易于处理,因为它们具有有意义的字符串值。

enum Weekend {
  Friday = 'FRIDAY',
  Saturday = 'SATURDAY',
  Sunday = 'SUNDAY'
}

It can then be used to compare strings in conditional statements like this:然后它可以用于比较条件语句中的字符串,如下所示:

enum Weekend {
  Friday = 'FRIDAY',
  Saturday = 'SATURDAY',
  Sunday ='SUNDAY'
}

const value = someString as Weekend;
if (value === Weekend.Friday || value === Weekend.Sunday){
    console.log('You choose a weekend');
    console.log(value); 
}

In the example above, we have defined a string enum, Weekend just like the numeric enum we had above, but this time with the enum values as strings.在上面的例子中,我们定义了一个字符串枚举,Weekend 就像我们上面的数字枚举一样,但这次将枚举值作为字符串。 The obvious difference between numeric and string enums is that numeric enum values are mostly sequentially incremented automatically, while string enum values are not incremented but rather each value is initialized independently.数字枚举和字符串枚举之间的明显区别在于,数字枚举值大多按顺序自动递增,而字符串枚举值不会递增,而是每个值独立初始化。

Heterogeneous enums TypeScript also allows for a mixture of both strings and numbers, called heterogeneous enum values:异构枚举TypeScript 还允许混合字符串和数字,称为异构枚举值:

enum Weekend {
  Friday = 'FRIDAY',
  Saturday = 1,
  Sunday = 2
}

Although this is possible, the range of scenarios that will likely require this use case is really small.尽管这是可能的,但可能需要此用例的场景范围非常小。 So unless you are really trying to take advantage of JavaScript's runtime behavior in a clever way, it is advised that you do not use heterogenous enums.因此,除非您真的想以巧妙的方式利用 JavaScript 的运行时行为,否则建议您不要使用异构枚举。

Computed enums The value of a numeric enum can either be constant or evaluated, just like any other number data type in TypeScript.计算枚举数字枚举的值可以是常量,也可以是计算值,就像 TypeScript 中的任何其他数字数据类型一样。 You can define or initialize your numeric enum with a computed value:您可以使用计算值定义或初始化您的数字枚举:

enum Weekend {
  Friday = 1,
  Saturday = getDate('TGIF'),
  Sunday = Saturday * 40
}

function getDate(day : string): number {
    if (day === 'TGIF') {
        return 3;
    }
}
Weekend.Saturday; // returns 3
Weekend.Sunday; // returns 120

Rule #1 —规则1 -

when enums include a mixture of computed and constant members, the enum members that are not initialized either come first or must come after other initialised members with numeric constants.当枚举包含计算成员和常量成员的混合时,未初始化的枚举成员要么首先出现,要么必须在其他具有数字常量的初始化成员之后。

Ignoring this rule above gives an initializer error — if you see that, remember to rearrange the enum members accordingly.忽略上面的这条规则会导致初始化错误——如果你看到了,记得相应地重新排列枚举成员。

Const enums If you want to boost the performance of your numeric enums you can declare them as a constant.常量枚举如果您想提高数字枚举的性能,您可以将它们声明为常量。 Let us use our weekend example to illustrate:让我们用周末的例子来说明:

enum Weekend {
  Friday = 1,
  Saturday,
  Sunday
}

var day = Weekend.Saturday;

When compiled to JavaScript , at execution the runtime looks up Weekend and looks up Weekend.Saturday.当编译为JavaScript ,运行时会在执行时查找 Weekend 并查找 Weekend.Saturday。 For optimal performance at runtime, you can make the enum a constant instead, like this:为了在运行时获得最佳性能,您可以将枚举改为常量,如下所示:

const enum Weekend {
  Friday = 1,
  Saturday,
  Sunday
}
var day = Weekend.Saturday;

The JavaScript generated at compile with the constant is thus:编译时使用常量生成的 JavaScript 是这样的:

var day = 2;

We see how the compiler just inlines the enum usages and does not even bother generating JavaScript for enum declarations when it sees the const.我们看到编译器如何只内联 enum 用法,甚至在看到 const 时都不会为 enum 声明生成 JavaScript。 It is important to be aware of this choice and the consequences when you have use cases that will require number to strings or strings to number lookups.当您有需要数字到字符串或字符串到数字查找的用例时,了解此选择及其后果很重要。 You can also pass the compiler flag — preserveConstEnums and it will still generate the Weekenddefinition.你也可以传递编译器标志——preserveConstEnums,它仍然会生成周末定义。

Reverse mapping TypeScript enums support reverse mapping, which simply means that just as we have access to the value of an enum member, we also have access to the enum name itself.反向映射TypeScript 枚举支持反向映射,这只是意味着就像我们可以访问枚举成员的值一样,我们也可以访问枚举名称本身。 A sample of our first demonstration is used to portray this below:我们第一个演示的示例用于描述以下内容:

enum Weekend {
  Friday = 1,
  Saturday,
  Sunday
}
Weekend.Saturday     
Weekend["Saturday"];  
Weekend[2];

In the code block above, Weekend.Saturday will return 2 and then Weekend["Saturday"] will also return 2 but interestingly, due to reverse mapping Weekend[2] will return its member name Saturday.在上面的代码块中,Weekend.Saturday 将返回 2,然后Weekend["Saturday"]也将返回 2 但有趣的是,由于反向映射, Weekend[2]将返回其成员名星期六。 This is because of reverse mapping.这是因为反向映射。 We can see a simple way TypeScript interprets reverse mapping with a log command:我们可以看到 TypeScript 使用 log 命令解释反向映射的一种简单方式:

enum Weekend {
  Friday = 1,
  Saturday,
  Sunday
}
console.log(Weekend);

If you run this in a console, you will see this output:如果您在控制台中运行它,您将看到以下输出:

{
  '1': 'Friday',
  '2': 'Saturday',
  '3': 'Sunday',
  Friday   : 1,
  Saturday : 2,
  Sunday  : 3
}

The objects contain the enums appearing both as values and as names, just as TypeScript intended.对象包含作为值和名称出现的枚举,正如 TypeScript 所期望的那样。 This shows the potency of reverse mapping in TypeScript.这显示了 TypeScript 中反向映射的潜力。

When to use TypeScript enums There are places and suitable use cases where it's optimal and very efficient to use enums何时使用 TypeScript 枚举在某些地方和合适的用例中,使用枚举是最佳且非常有效的

Enums can be used inside array initialisations just as other TypeScript data types枚举可以像其他 TypeScript 数据类型一样在数组初始化中使用

Here is a quick example:这是一个快速示例:

enum NigerianLanguage {
  Igbo,
  Hause, 
  Yoruba
}

//can be used in array initialisation 
let citizen = {
  Name: 'Ugwunna',
  Age: 75,
  Language: NigerianLanguage.Igbo
}

Enums should ideally be used in situations where there are distinct values that can be seen as constants, like seven days of the week:理想情况下,应该在存在可以视为常量的不同值的情况下使用枚举,例如一周中的 7 天:

enum Days {
  Sunday = 1,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}

Enums can also be used in places where strings or constants need to be represented in a variable.枚举也可用于需要在变量中表示字符串或常量的地方。

Simplest solution would be to just use a string enum :最简单的解决方案是只使用string enum

enum Status {
    start = 'start',
    loading = 'loading',
    stop = 'stop'
}


class Loading {
    static staticStatus: Status;
}

Loading.staticStatus = Status.loading;

More更多的

String enums 字符串枚举

In my case, i use next就我而言,我使用 next

import { IExternal } from 'external';

enum Types = {
   FIRST = 'first',
   SECOND = 'second'
}

interface IInternal extends Pick<IExternal, 'types'> {
    types: Types
}

IExternal['types'] === 'first' | IExternal['types'] === 'first' | 'second' | '第二' | 'something' | '东西' | 'else'; '别的';

IInternal['types'] === 'first' | IInternal['types'] === 'first' | 'second'; '第二'; and compatible with IExternal['types']并与 IExternal['types'] 兼容

It allow you to use types from union as enum values and give you compatible check.它允许您使用 union 中的类型作为枚举值并为您提供兼容检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM