0
0
Typescriptprogramming~10 mins

Control flow analysis behavior 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 check if the variable is a string.

Typescript
function checkType(value: unknown) {
  if (typeof value === [1]) {
    return true;
  }
  return false;
}
Drag options to blanks, or click blank then click option'
A"number"
B"string"
C"boolean"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the type name without quotes.
Checking for 'String' instead of 'string'.
2fill in blank
medium

Complete the code to narrow the type using a type guard.

Typescript
function process(value: string | number) {
  if (typeof value === [1]) {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}
Drag options to blanks, or click blank then click option'
A"string"
B"number"
C"boolean"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for 'number' instead of 'string'.
Calling string methods on number types.
3fill in blank
hard

Fix the error by completing the code to correctly narrow the type.

Typescript
function example(value: string | null) {
  if (value [1] null) {
    return value.length;
  }
  return 0;
}
Drag options to blanks, or click blank then click option'
A!==
B!=
C===
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == which allows type coercion.
Checking for equality instead of inequality.
4fill in blank
hard

Fill both blanks to create a type guard that checks for an array of numbers.

Typescript
function isNumberArray(value: unknown): value is number[] {
  return Array.isArray(value) && value.every(item => typeof item [1] [2]);
}
Drag options to blanks, or click blank then click option'
A===
B"number"
C==
D"string"
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of ===.
Comparing to "string" instead of "number".
5fill in blank
hard

Fill all three blanks to create a function that narrows a union type using control flow.

Typescript
function formatValue(value: string | number | boolean) {
  switch (typeof value) {
    case [1]:
      return value.toUpperCase();
    case [2]:
      return value.toFixed(1);
    case [3]:
      return value ? "Yes" : "No";
  }
}
Drag options to blanks, or click blank then click option'
A"string"
B"number"
C"boolean"
D"object"
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect type strings like "object".
Mixing up the order of cases.