TypeScript: Form errors with a mapped type

Validate sign-up forms and collect one error message per field in an object whose type is mapped from the form.

What to build

A program that validates forms and reports their errors.

Requirements

  • Declare interface SignUp { name: string; email: string; age: string } and type FormErrors<T> = { [K in keyof T]?: string }.
  • Rules: name must not be empty (required); email must contain @ and a . after it (not an email); age must be a whole number (not a number) from 13 to 120 (must be 13 to 120).
  • Print form I: ok or form I: FIELD: MESSAGE; FIELD: MESSAGE with fields in the order name, email, age; forms are numbered from 1.

Input

Line 1: n. Then n lines name;email;age.

Output

n lines.

Constraints

1 ≤ n ≤ 50.

Example

Input:

3
Ada;ada@example.com;36
;bob@example;12
Cy;cy@site.org;abc

Output:

form 1: ok
form 2: name: required; email: not an email; age: must be 13 to 120
form 3: age: not a number

Why it works

Mapping the errors type from the form type means the errors object can only have keys the form has, so a typo in a field name is a compile error, and a new form field becomes a field that may have an error.

Examples

Example 1 · Input
3
Ada;ada@example.com;36
;bob@example;12
Cy;cy@site.org;abc
Expected output
form 1: ok
form 2: name: required; email: not an email; age: must be 13 to 120
form 3: age: not a number
Example 2 · Input
1
Dee;@x.org;20
Expected output
form 1: email: not an email

Hints

Hint 1

type FormErrors<T> = { [K in keyof T]?: string } has an optional message for every field of T.

Hint 2

Check the fields in the order name, email, age and collect the messages.

Solution

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

interface SignUp {
  name: string;
  email: string;
  age: string;
}

type FormErrors<T> = { [K in keyof T]?: string };
const FIELDS: (keyof SignUp)[] = ["name", "email", "age"];

function validate(form: SignUp): FormErrors<SignUp> {
  const errors: FormErrors<SignUp> = {};
  if (form.name.trim() === "") errors.name = "required";
  const at = form.email.indexOf("@");
  if (at < 1 || form.email.indexOf(".", at) === -1) errors.email = "not an email";
  if (!/^\d+$/.test(form.age)) errors.age = "not a number";
  else if (Number(form.age) < 13 || Number(form.age) > 120) errors.age = "must be 13 to 120";
  return errors;
}

const n = Number(read());
for (let i = 1; i <= n; i++) {
  const [name, email, age] = read().split(";");
  const errors = validate({ name, email, age });
  const parts = FIELDS.filter((f) => errors[f] !== undefined).map((f) => f + ": " + errors[f]);
  console.log("form " + i + ": " + (parts.length ? parts.join("; ") : "ok"));
}

Lesson: Mapped, conditional and template literal types →