Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert union type to enum in typescript?

Tags:

typescript

I want to covert union type to enum or like enum in typescript

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...

like image 302
bugtype kr Avatar asked Jul 09 '19 02:07

bugtype kr


People also ask

How to convert enum to type in TypeScript?

Use a template literal type to convert an enum to a union type, e.g. type ValuesUnion = ${StringEnum} . Template literal types have the same syntax as template literal strings. The union type will contain all of the values of the enum.

When to use enum vs union?

Code Size Difference You will see a difference in the code size once TypeScript code is compiled into JavaScript code. Using string literal unions will “reduce” or not change the size of your code. On the other hand, using enums will increase the code size.

Is enum a union type?

Enums can be seen conceptually as a subset of union types, dedicated to int and/or string values, with a few additional features mentioned in other responses that make them friendly to use, e.g. namespace.

When to use type vs enum TypeScript?

Enums allow us to define or declare a collection of related values that can be numbers or strings as a set of named constants. Unlike some of the types available in TypeScript, enums are preprocessed and are not tested at compile time or runtime.


1 Answers

Not sure how you would get an enum from a Union but you can easily do the reverse if you need both.

enum Status {
 start,
 loading,
 stop
}

type StatusAsUnion = keyof typeof Status

Hopefully this was useful

like image 191
Mateusz Siniarski Avatar answered Sep 24 '22 00:09

Mateusz Siniarski