0
0
Typescriptprogramming~20 mins

Control flow analysis behavior in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Control Flow Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Control flow narrowing with type guards
What is the output of this TypeScript code when calling processValue(42)?
Typescript
function processValue(value: string | number) {
  if (typeof value === 'string') {
    return value.toUpperCase();
  } else {
    return value.toFixed(2);
  }
}

console.log(processValue(42));
A"42.0"
B"42"
C"42.00"
DTypeError at runtime
Attempts:
2 left
💡 Hint
Think about how TypeScript narrows the type inside the if-else blocks.
Predict Output
intermediate
2:00remaining
Control flow with union types and null checks
What will be logged when running this TypeScript code?
Typescript
function greet(name: string | null) {
  if (name) {
    console.log(`Hello, ${name.toUpperCase()}!`);
  } else {
    console.log("Hello, guest!");
  }
}

greet(null);
AHello, null!
BHello, NULL!
CTypeError: Cannot read property 'toUpperCase' of null
DHello, guest!
Attempts:
2 left
💡 Hint
Check how the if condition treats null values.
Predict Output
advanced
2:00remaining
Control flow with discriminated unions and exhaustive checks
What is the output of this TypeScript code?
Typescript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; size: number };

function area(shape: Shape) {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.size ** 2;
  }
}

console.log(area({ kind: "circle", radius: 3 }));
A28.274333882308138
B9
Cundefined
DTypeError at runtime
Attempts:
2 left
💡 Hint
Recall the formula for the area of a circle and how discriminated unions work.
Predict Output
advanced
2:00remaining
Control flow with type narrowing and assignment
What will be the value of result after running this TypeScript code?
Typescript
let input: string | number = "hello";

if (typeof input === "string") {
  input = input.length;
}

const result = input;
ATypeError at runtime
B5
C"hello"
Dundefined
Attempts:
2 left
💡 Hint
Check how the variable 'input' is reassigned inside the if block.
Predict Output
expert
2:00remaining
Control flow with type predicates and custom type guards
What is the output of this TypeScript code?
Typescript
interface Fish {
  swim(): void;
}

interface Bird {
  fly(): void;
}

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    return "Fish swims";
  } else {
    return "Bird flies";
  }
}

console.log(move({ fly() { console.log('flying'); } }));
A"Bird flies"
B"Fish swims"
CTypeError at runtime
Dundefined
Attempts:
2 left
💡 Hint
Understand how the custom type guard function works.