0
0
Typescriptprogramming~10 mins

Literal types and value narrowing 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 variable with a literal type.

Typescript
let direction: 'up' | 'down' = [1];
Drag options to blanks, or click blank then click option'
A"left"
B"up"
C"right"
D"forward"
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning a string not in the literal type union.
Forgetting to use quotes around the string.
2fill in blank
medium

Complete the function to narrow the literal type using a switch statement.

Typescript
function move(direction: 'left' | 'right') {
  switch (direction) {
    case [1]:
      return 'Moving left';
    case 'right':
      return 'Moving right';
  }
}
Drag options to blanks, or click blank then click option'
A"left"
B"up"
C"down"
D"forward"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string not in the union type.
Omitting quotes around the case value.
3fill in blank
hard

Fix the error in the type narrowing by completing the if condition.

Typescript
function isYes(answer: 'yes' | 'no'): boolean {
  if (answer === [1]) {
    return true;
  }
  return false;
}
Drag options to blanks, or click blank then click option'
A"no"
B"maybe"
C"y"
D"yes"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking against a string not in the union type.
Using loose equality instead of strict equality.
4fill in blank
hard

Fill both blanks to create a function that narrows a literal type and returns a message.

Typescript
function getStatus(status: 'success' | 'error') {
  if (status === [1]) {
    return 'Operation was successful';
  } else if (status === [2]) {
    return 'Operation failed';
  }
}
Drag options to blanks, or click blank then click option'
A"success"
B"fail"
C"error"
D"pending"
Attempts:
3 left
💡 Hint
Common Mistakes
Using strings not in the union type.
Mixing up the order of the literals.
5fill in blank
hard

Fill all three blanks to create a function that narrows a literal type and returns a custom message.

Typescript
function respond(action: 'start' | 'stop' | 'pause') {
  if (action === [1]) {
    return 'Starting';
  } else if (action === [2]) {
    return 'Stopping';
  } else if (action === [3]) {
    return 'Pausing';
  }
}
Drag options to blanks, or click blank then click option'
A"start"
B"stop"
C"pause"
D"play"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string not in the union type.
Forgetting quotes around string literals.