Skip to content
FrontDepth, Home

Back to the topic

Practice: Narrowing, type guards and unknown

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

4 predict-output · 4 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputJunior

    Two functions decide whether there is a count to show. Both type-check under --strict. What does it log?

    TypeScript
    function withTruthiness(count: number | undefined): string {
      if (count) return `${count} new`;
      return "no data";
    }
    
    function withUndefinedCheck(count: number | undefined): string {
      if (count !== undefined) return `${count} new`;
      return "no data";
    }
    
    console.log(withTruthiness(3));
    console.log(withTruthiness(0));
    console.log(withUndefinedCheck(0));
    console.log(withUndefinedCheck(undefined));
    console.log(withTruthiness(NaN));
  2. Open questionJunior

    What is narrowing in TypeScript, and which JavaScript checks does it understand?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  3. Predict the outputMiddle

    farewell checks session.user and then calls signOut(). The code type-checks under --strict. What does it log?

    TypeScript
    type Session = { user: { name: string } | null };
    
    const session: Session = { user: { name: "Ada" } };
    
    function signOut(): void {
      session.user = null;
    }
    
    function farewell(): string {
      if (session.user !== null) {
        signOut();
        return `Bye, ${session.user.name}`;
      }
      return "Nobody to sign out";
    }
    
    try {
      console.log(farewell());
    } catch (error) {
      console.log(error instanceof TypeError ? "TypeError" : "another error");
    }
  4. Predict the outputMiddle

    badge handles every member of Status and calls assertNever in default. The list comes from the server and is cast with as Status[]. The code type-checks under --strict. What does it log?

    TypeScript
    type Status = "active" | "suspended";
    
    function assertNever(value: never): never {
      throw new Error(`Unhandled status: ${String(value)}`);
    }
    
    function badge(status: Status): string {
      switch (status) {
        case "active":
          return "green";
        case "suspended":
          return "grey";
        default:
          return assertNever(status);
      }
    }
    
    const fromServer = JSON.parse('["active", "deleted", "suspended"]') as Status[];
    
    for (const status of fromServer) {
      try {
        console.log(badge(status));
      } catch (error) {
        console.log(error instanceof Error ? error.message : "unknown error");
      }
    }
  5. Open questionMiddle

    Why is unknown safer than any, and how do you handle the value in a catch block?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  6. Open questionMiddle

    What is a discriminated union, and how do you make TypeScript tell you when a case is not handled?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  7. Predict the outputSenior

    isContact is a type guard, used with filter. The code type-checks under --strict. What does it log?

    TypeScript
    interface Contact {
      name: string;
      email: string;
    }
    
    function isContact(value: unknown): value is Contact {
      return typeof value === "object" && value !== null && "name" in value;
    }
    
    const rows: unknown[] = JSON.parse(
      '[{"name":"Ada","email":"ada@example.com"},{"name":"Linus"},"Grace"]',
    );
    
    const contacts = rows.filter(isContact);
    console.log(contacts.length);
    
    for (const contact of contacts) {
      try {
        console.log(contact.email.toLowerCase());
      } catch {
        console.log(`crash on ${contact.name}`);
      }
    }
  8. Open questionSenior

    What are user-defined type guards and assertion functions, how do they differ, and why can a type guard lie?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.