TypeScript · Middle · Question 1 of 75
What is a user-defined type guard?
function isUser(x: unknown): x is User {
return typeof x === "object" && x !== null && "id" in x;
}- ✓Correct answer: A function with the return type
x is Tthat narrows the argument whentrue - 2A decorator that checks the argument type at runtime on every call
- 3Type assertion syntax equivalent to writing
x as Userin code
Explanation
After if (isUser(data)), data has type User inside the branch. The developer is responsible for the check being correct: the compiler trusts the predicate. Since TS 5.5, simple predicates are inferred automatically, e.g. for arr.filter(x => x !== null).