0
0
Typescriptprogramming~10 mins

When enums add unnecessary runtime code in Typescript - Interactive Code Practice

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

Complete the code to declare a string enum with two colors.

Typescript
enum Colors {
  Red = [1],
  Blue = "blue"
}
Drag options to blanks, or click blank then click option'
A'red'
Bred
CRed
D"red"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around string values.
Using variable names instead of string literals.
2fill in blank
medium

Complete the code to define a union type instead of an enum for colors.

Typescript
type Colors = [1];
Drag options to blanks, or click blank then click option'
Aenum { red, blue }
B"red" | "blue"
C["red", "blue"]
D"red", "blue"
Attempts:
3 left
💡 Hint
Common Mistakes
Using enum keyword instead of union type.
Using array syntax instead of union.
3fill in blank
hard

Fix the error in the code by replacing the enum with a union type to avoid runtime code.

Typescript
enum Status {
  Active,
  Inactive
}

function checkStatus(status: [1]) {
  return status === "Active";
}
Drag options to blanks, or click blank then click option'
A"Active" | "Inactive"
BStatus
Cstring
Dnumber
Attempts:
3 left
💡 Hint
Common Mistakes
Using the enum type which is numeric by default.
Using plain string type which is too broad.
4fill in blank
hard

Fill both blanks to create a union type and a function that accepts only those values.

Typescript
type Direction = [1];

function move(dir: Direction): void {
  console.log("Moving", dir);
}

move([2]);
Drag options to blanks, or click blank then click option'
A"up" | "down" | "left" | "right"
B"up"
C"forward"
D"left"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a string not in the union.
Using enum instead of union type.
5fill in blank
hard

Fill all three blanks to rewrite the enum as a union type and use it in a function with a default parameter.

Typescript
type Status = [1];

function setStatus(status: Status = [2]): string {
  return `Status is ${status}`;
}

console.log(setStatus([3]));
Drag options to blanks, or click blank then click option'
A"online" | "offline" | "away"
B"online"
C"offline"
D"away"
Attempts:
3 left
💡 Hint
Common Mistakes
Using enum instead of union type.
Default value not in the union.
Function call uses invalid status.