w3resource

TypeScript Enumeration: Define and Assign Values

TypeScript Basic: Exercise-9 with Solution

Write a TypeScript program that defines an enumeration 'Color' with values 'Red', 'Green', 'White' and Blue. Create a variable 'selectedColor' of type 'Color' and assign it one of the enumeration values.

Sample Solution:

TypeScript Code:

// Define an enumeration (enum) for colors
enum Color {
  Red,
  Green,
  White,
  Blue,
}
console.log("List of colors:",Color);
// Create a variable 'selectedColor' of type 'Color' and assign a value from the enumeration
let selectedColor: Color = Color.Green;

// Print the selected color
console.log("Selected Color:", selectedColor);

Explanations:

In the exercise above -

  • Define an enumeration 'Color' using the 'enum' keyword and specify its values as 'Red', 'Green', 'White', and 'Blue'. By default, TypeScript assigns numeric values to each enumeration member starting from 0 (e.g., Red is 0, Green is 1, and so on).
  • Create a variable 'selectedColor' of type 'Color' and assign it the value Color.Green, which corresponds to the 'Green' enumeration member.
  • Use console.log to print the value of 'selectedColor' to the console.

Output:

"List of colors:"
[object Object] {
  0: "Red",
  1: "Green",
  2: "White",
  3: "Blue",
  Blue: 3,
  Green: 1,
  Red: 0,
  White: 2
}
"Selected Color:"
1

TypeScript Editor:

See the Pen TypeScript by w3resource (@w3resource) on CodePen.


Previous: TypeScript array operations: Add, remove, iterate.
Next: Working with null and undefined in TypeScript.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.