we usually use Enum or union type using typescript.
they are defined sets of values in programming, but they serve different purposes.
Today, we are going to find out about these.
we can make a similar type using those two type.
a union type is a type can hold one of several types.
type DeviceType = "phone" | "pad" | "deskTop"
An enumm defines a set of named values.
enum DeviceType {
phone="phone",
pad="pad",
deskTop="deskTop"
}
enum Fruit {
APPLE,
BANANA
}
enum AnotherFruit{
PINEAPPLE
}
type Fruit = Fruit | AnotherFruit
enum Fruit {
APPLE = 'APPLE',
BANANA = "BANANA"
}
getSomeFruit('APPLE') // X
getSomeFruit(Fruit.APPLE) // O
enum Status{
pedding=0,
success=1,
fail=2
}
const newStatus: Status = 100; // none error here..
and an Enum an be replaced by object also.
const Device = {
phone="phone",
pad="pad",
deskTop="deskTop"
} as const
type DeviceType = typeof Device[keyof typeof Device]
Reverse mapping
enum Color {
Red = 1,
Green,
Blue
}
// Forward mapping
console.log(Color.Red); // Output: 1
console.log(Color.Green); // Output: 2
// Reverse mapping
console.log(Color[1]); // Output: "Red"
console.log(Color[2]); // Output: "Green"