TypeScript: Name the type of JSON values

Values that arrive while a program runs have no static type. Read lines of JSON and report what kind of value each one is.

What to build

A program that parses each line as JSON and names its kind.

Requirements

  • Parse each line with JSON.parse into a variable of type unknown.
  • Print LINE -> KIND, where KIND is array for an array, null for null, and otherwise what typeof gives (number, string, boolean or object).
  • If the line is not valid JSON, print LINE -> not JSON.

Input

Line 1: n. Then n lines.

Output

n lines.

Constraints

1 ≤ n ≤ 50.

Example

Input:

4
42
"hello"
[1, 2, 3]
null

Output:

42 -> number
"hello" -> string
[1, 2, 3] -> array
null -> null

Why it works

unknown is the honest type for parsed data: TypeScript lets you use it only after a check, and the checks must test arrays and null first because typeof calls both of them "object".

Examples

Example 1 · Input
4
42
"hello"
[1, 2, 3]
null
Expected output
42 -> number
"hello" -> string
[1, 2, 3] -> array
null -> null
Example 2 · Input
3
{"name": "Ada"}
true
hello
Expected output
{"name": "Ada"} -> object
true -> boolean
hello -> not JSON

Hints

Hint 1

JSON.parse can throw: put it in try ... catch.

Hint 2

Store the parsed value as unknown, then check it with Array.isArray, === null and typeof.

Solution

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

function kindOf(value: unknown): string {
  if (Array.isArray(value)) return "array";
  if (value === null) return "null";
  return typeof value;
}

const n = Number(read());
for (let i = 0; i < n; i++) {
  const line = read();
  let kind: string;
  try {
    const value: unknown = JSON.parse(line);
    kind = kindOf(value);
  } catch {
    kind = "not JSON";
  }
  console.log(line + " -> " + kind);
}

Lesson: Why TypeScript →