Skip to content
FrontDepth, Home

Back to the topic

Practice: Validating data at the boundary

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

3 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

    Settings saved by an older version of the app are read back with JSON.parse and an as assertion. What does it log?

    TypeScript
    type ViewSettings = { pageSize: number; view: "grid" | "list" };
    
    const saved = '{"pageSize":"20","view":"table"}';
    const settings = JSON.parse(saved) as ViewSettings;
    
    console.log(typeof settings.pageSize);
    console.log(settings.pageSize + 5);
    console.log(settings.view === "grid" ? "grid" : "list");
    console.log(settings.view);
  2. Open questionJunior

    Why doesn't const user = (await response.json()) as User make the data safe, and what does?

    Think it through first

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

  3. Open questionJunior

    What is the difference between a type annotation, satisfies and as?

    Think it through first

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

  4. Predict the outputMiddle

    URL parameters are strings or null, and they usually have to become numbers. What does this log?

    TypeScript
    const params = new URLSearchParams("?page=2&page=5&size=&limit=1e3&q=+tea");
    
    console.log(params.get("page"));
    console.log(JSON.stringify(params.getAll("page")));
    console.log(JSON.stringify(params.get("size")));
    console.log(params.get("sort"));
    console.log(Number(params.get("size")));
    console.log(Number(params.get("sort")));
    console.log(Number(params.get("limit")));
    console.log(JSON.stringify(params.get("q")));
  5. Open questionMiddle

    What does "parse, don't validate" mean, and how does a schema library like Zod apply it?

    Think it through first

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

  6. Predict the outputSenior

    A small hand-written parser in the style of a schema library: it takes unknown, collects every issue with its path, and returns either typed data or the issues. What does it log for the three inputs?

    TypeScript
    type Issue = { path: string; message: string };
    type Result<T> = { success: true; data: T } | { success: false; issues: Issue[] };
    type Line = { sku: string; qty: number };
    
    function isRecord(value: unknown): value is Record<string, unknown> {
      return typeof value === "object" && value !== null && !Array.isArray(value);
    }
    
    function parseLine(input: unknown, path: string, issues: Issue[]): Line | undefined {
      if (!isRecord(input)) {
        issues.push({ path, message: "expected object" });
        return undefined;
      }
      const { sku, qty } = input;
      const skuOk = typeof sku === "string";
      const qtyOk = typeof qty === "number" && Number.isInteger(qty) && qty >= 1;
      if (!skuOk) issues.push({ path: path + ".sku", message: "expected string" });
      if (!qtyOk) issues.push({ path: path + ".qty", message: "expected integer >= 1" });
      return skuOk && qtyOk ? { sku, qty } : undefined;
    }
    
    function parseCart(input: unknown): Result<Line[]> {
      if (!Array.isArray(input)) return { success: false, issues: [{ path: "cart", message: "expected array" }] };
      const issues: Issue[] = [];
      const lines: Line[] = [];
      input.forEach((item, i) => {
        const line = parseLine(item, `cart[${i}]`, issues);
        if (line) lines.push(line);
      });
      return issues.length > 0 ? { success: false, issues } : { success: true, data: lines };
    }
    
    function show(result: Result<Line[]>): string {
      if (result.success) return "ok " + JSON.stringify(result.data);
      return "failed " + result.issues.map((i) => i.path + " " + i.message).join("; ");
    }
    
    console.log(show(parseCart(JSON.parse('[{"sku":"tea","qty":2,"price":1}]'))));
    console.log(show(parseCart(JSON.parse('[{"sku":"tea","qty":"2"},null,{"qty":0}]'))));
    console.log(show(parseCart(JSON.parse('{"sku":"tea","qty":2}'))));
  7. Open questionSenior

    Where in a frontend app would you validate data, and how should invalid data be handled for each source?

    Think it through first

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