Search This Blog

2023/09/10

ENUM Replacement in Typescript

 ENUM Declartion


//ENUM Declartion
enum Direction {
UP,
DOWN
}

function move(direction: Direction) {
console.log(direction)
}

move(Direction.UP);



ENUM REPLACEMENTS

By Using String Union


function move(direction: Direction) {
console.log(direction)
}

type Direction = "UP" | "DOWN";

move("UP")


Using Object Literals


const DIRECTIONS = {
UP: "UP",
DOWN: "DOWN"
} as const;

type Direction = typeof DIRECTIONS[keyof typeof DIRECTIONS];


function move(direction: Direction) {
console.log(direction)
}


move("DOWN")

No comments:

Post a Comment