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;
}

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).

Further reading

Problem with a question

TypeScript · Middle · question 1

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz