TypeScript: Validate users with a type guard

Data from outside a program has no guaranteed type. Check each record with a type guard before using it.

What to build

A program that validates JSON records as users.

Requirements

  • Declare interface User { name: string; age: number }.
  • For each line, if it is a valid user print valid: NAME (AGE).
  • Otherwise print the first problem, checked in this order: invalid: not JSON, invalid: not an object (null and arrays are not objects here), invalid: name must be a string, invalid: age must be a number.

Input

Line 1: n. Then n lines of text.

Output

n lines.

Constraints

1 ≤ n ≤ 50.

Example

Input:

3
{"name": "Ada", "age": 36}
{"name": "Alan"}
[1, 2]

Output:

valid: Ada (36)
invalid: age must be a number
invalid: not an object

Why it works

unknown makes every field access wait for a check, and naming the checks as a type guard lets the code after it use name and age with their real types.

Examples

Example 1 · Input
3
{"name": "Ada", "age": 36}
{"name": "Alan"}
[1, 2]
Expected output
valid: Ada (36)
invalid: age must be a number
invalid: not an object
Example 2 · Input
2
{"name": 7, "age": 1}
not json
Expected output
invalid: name must be a string
invalid: not JSON

Hints

Hint 1

isUser(x: unknown): x is User checks the object, then each field.

Hint 2

Test typeof x === "object", x !== null and !Array.isArray(x) before looking at fields.

Solution

Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";

interface User {
  name: string;
  age: number;
}

function problemWith(x: unknown): string | null {
  if (typeof x !== "object" || x === null || Array.isArray(x)) return "not an object";
  if (!("name" in x) || typeof x.name !== "string") return "name must be a string";
  if (!("age" in x) || typeof x.age !== "number") return "age must be a number";
  return null;
}

function isUser(x: unknown): x is User {
  return problemWith(x) === null;
}

const n = Number(read());
for (let i = 0; i < n; i++) {
  let value: unknown;
  try {
    value = JSON.parse(read());
  } catch {
    console.log("invalid: not JSON");
    continue;
  }
  if (isUser(value)) console.log("valid: " + value.name + " (" + value.age + ")");
  else console.log("invalid: " + problemWith(value));
}

Lesson: Narrowing: from a union to one type →