Skip to content

QuizNot attempted

Type guards

What makes function isUser(x: unknown): x is User different from returning boolean?
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • When it returns true, TS narrows x to User at the call site
  • A type predicate x is User tells the compiler to narrow x to User in the true branch at the call site
  • a plain boolean return gives no narrowing.
  • Not a runtime check: TS trusts your implementation and emits nothing, so a wrong guard silently lies.
  • Not throws: it returns true/false
  • throwing is an assertion function (asserts x is User).
  • Not 'nothing': the narrowing is the whole point.
  • Validate untrusted data with a schema (zod).