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...
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With