Enums in TypeScript
Harsh Chandwani
2 min read
Here is the typescript file where I have compared enums with types
//Okay now lets do this
//basically when want to have a function, that should only some particular values, and it will be string
//one option is to create a if statment that can handle unknown situations (string)
//other people use in typescript is type
type keyInput = "up" | "down" | "left" | "right";
function doSomething(keyPressed: keyInput){
//do something
if(keyPressed == "up"){
console.log(keyPressed);
}
}
doSomething("up");
doSomething("down");
/*
but what are enums, (they are more human-readable, that why we use, and that will make us understand other
developer code to be much easier and readable)
*/
//here are the enums
enum Direction {
Up,
Down,
Right,
Left
}
function doSomething1(keyPressed: Direction){
//so something
if(keyPressed == Direction.Up){
console.log(Direction.Up);
}
}
doSomething1(Direction.Right);
And here is how the .js file has came up
"use strict";
//Okay now lets do this
//basically when want to have a function, that should only some particular values, and it will be string
//one option is to create a if statment that can handle unknown situations (string)
//other people use in typescript is type
function doSomething(keyPressed) {
//do something
if (keyPressed == "up") {
console.log(keyPressed);
}
}
doSomething("up");
doSomething("down");
/*
but what are enums, (they are more human-readable, that why we use, and that will make us understand other
developer code to be much easier and readable)
*/
//here are the enums
var Direction;
(function (Direction) {
Direction[Direction["Up"] = 0] = "Up";
Direction[Direction["Down"] = 1] = "Down";
Direction[Direction["Right"] = 2] = "Right";
Direction[Direction["Left"] = 3] = "Left";
})(Direction || (Direction = {}));
function doSomething1(keyPressed) {
//so something
if (keyPressed == Direction.Up) {
console.log(Direction.Up);
}
}
doSomething1(Direction.Right);
Hope you understand the difference and go on with your typescript journey.
Thank you
Harsh Chandwani
Software Developer
0
Subscribe to my newsletter
Read articles from Harsh Chandwani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Harsh Chandwani
Harsh Chandwani
Software Dev | 22 Years Old | Final Year Student | MERN Developer | GDSC Technical Core Member | ex- GeeksforGeeks | Writer | Poet |