Check Unknown Data with a Type Guard

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Data from outside (a parsed JSON body, say) arrives as unknown. Export a User type with a numeric id, a string name and an optional string email, and write isUser(value): true only for an object with those fields of those types. Make it a type guard, so that after if (isUser(value)) the compiler treats value as a User.

Your code must pass

  • Accepts users, with or without an email
  • Rejects anything else
  • Has no type errors
  • Narrows unknown to User
  • Is a type guard on unknown