TypeScript: Describe parsed values

Turn each line into the most fitting type, then narrow the union to describe it.

What to build

A program that describes each input value according to its type.

Requirements

  • parse returns null for an empty line, true or false for true and false, a number for numeric text, and the text otherwise.
  • Print empty for null, number N, doubled D for a number, boolean, negated X for a boolean, and text of K characters for a string.

Input

Line 1: n. Then n lines.

Output

n lines.

Constraints

1 ≤ n ≤ 50.

Example

Input:

4
21
true
hello

Output:

number 21, doubled 42
boolean, negated false
text of 5 characters
empty

Why it works

Returning a union from parse and narrowing it in describe keeps the two jobs apart, and after null, number and boolean are handled TypeScript knows that only a string can be left.

Examples

Example 1 · Input
4
21
true
hello

Expected output
number 21, doubled 42
boolean, negated false
text of 5 characters
empty
Example 2 · Input
2
-1.5
false
Expected output
number -1.5, doubled -3
boolean, negated true

Hints

Hint 1

Write parse(text: string): number | boolean | null | string.

Hint 2

In describe, check null first, then typeof for number and boolean; only string is left.

Solution

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

function parse(text: string): number | boolean | null | string {
  if (text === "") return null;
  if (text === "true" || text === "false") return text === "true";
  if (!Number.isNaN(Number(text))) return Number(text);
  return text;
}

function describe(value: number | boolean | null | string): string {
  if (value === null) return "empty";
  if (typeof value === "number") return "number " + value + ", doubled " + value * 2;
  if (typeof value === "boolean") return "boolean, negated " + !value;
  return "text of " + value.length + " characters";
}

const n = Number(read());
for (let i = 0; i < n; i++) console.log(describe(parse(read())));

Lesson: Narrowing: from a union to one type →