switch typescript
- Enums allow a developer to define a set of named constants.
- An enum allows a collection of values to be used by name.
- TypeScript provides both numeric and string-based enums.
typescript switch
- A switch statement is a control-flow statement that tests the value of an expression against multiple cases.
- Create a reusable function that takes an enum value as a parameter. Use a switch statement and switch on the provided value.
An enum can contain both string and number values
enum Pets { Lizard = 'lizard', Dog = 'dog', Cat = 'cat', Snake = 'snake', Parrot = 'parrot' } function getPet(petName : Pets) { switch (petName) { case Pets.Lizard: console.log("I own a lizard"); break; case Pets.Dog: console.log("I own a dog"); break; case Pets.Cat: console.log("I own a cat"); break; case Pets.Snake: console.log("I own a snake"); break; case Pets.Parrot: console.log("I own a parrot"); break; default: console.log("I don't own a pet"); break; } } getPet(Pets.Dog) getPet(Pets.Parrot)
If you run the code from the example above,
Output
I own a dog I own a parrot