0 of 6 problems solved0%
2 of 6

Safe JSON Title

JSON.parse returns any. Replace this with unknown and add checks. You will parse JSON, then safely read a title if it exists and is a string.

Check that the value is an object and not null before reading properties. Then check that title is a string.

function readName(v: unknown) {
  if (typeof v === "object" && v !== null && "name" in v) {
    const n = (v as { name?: unknown }).name;
    return typeof n === "string" ? n : "unknown";
  }
  return "unknown";
}

Your Task

Parse JSON and return a safe title string.

  • Implement safeParse(json: string): unknown that returns JSON.parse(json).
  • Implement readTitle(v: unknown): string.
  • If v is an object and has a string title, return it; otherwise return 'untitled'.
  • Keep both functions pure.