Reputation: 455
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...
Upvotes: 40
Views: 29312
Reputation: 83
In my case, i use next
import { IExternal } from 'external';
enum Types = {
FIRST = 'first',
SECOND = 'second'
}
interface IInternal extends Pick<IExternal, 'types'> {
types: Types
}
IExternal['types'] === 'first' | 'second' | 'something' | 'else';
IInternal['types'] === 'first' | 'second'; and compatible with IExternal['types']
It allow you to use types from union as enum values and give you compatible check.
Upvotes: -1
Reputation: 1015
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
Upvotes: 37