0
0
Typescriptprogramming~10 mins

Enum vs union literal type trade-offs in Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a union literal type for colors.

Typescript
type Color = [1];
Drag options to blanks, or click blank then click option'
A"red" | "green" | "blue"
Benum Color { Red, Green, Blue }
Cstring
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using enum syntax instead of union literal type.
Using a general string type instead of specific literals.
2fill in blank
medium

Complete the code to declare an enum for colors.

Typescript
enum Color { [1] }
Drag options to blanks, or click blank then click option'
ARed = "red", Green = "green", Blue = "blue"
B"red" | "green" | "blue"
Cred, green, blue
D1, 2, 3
Attempts:
3 left
💡 Hint
Common Mistakes
Using union literal syntax inside enum.
Listing values without identifiers.
3fill in blank
hard

Fix the error in this enum usage to get the string value.

Typescript
const colorName: string = Color[1]Red;
Drag options to blanks, or click blank then click option'
A["Red"]
B[Red]
C.Red
DRed
Attempts:
3 left
💡 Hint
Common Mistakes
Using brackets instead of dot notation.
Omitting the dot before member name.
4fill in blank
hard

Fill both blanks to define a function accepting only specific colors.

Typescript
function paint(color: [1]): void {
  console.log(`Painting with ${color}`);
}

paint([2]);
Drag options to blanks, or click blank then click option'
A"red" | "green" | "blue"
BColor.Red
C"yellow"
Dstring
Attempts:
3 left
💡 Hint
Common Mistakes
Using a general string type for the parameter.
Passing a string not in the union type.
5fill in blank
hard

Fill all three blanks to create a type guard for enum or union literal types.

Typescript
function isColor(value: any): value is [1] {
  return typeof value === [2] && [3];
}
Drag options to blanks, or click blank then click option'
A"red" | "green" | "blue"
B"string"
C(value === "red" || value === "green" || value === "blue")
DColor
Attempts:
3 left
💡 Hint
Common Mistakes
Using enum type in the type guard without proper checks.
Incorrect logical OR syntax in the return statement.