Type guards

suggest change

Built-in narrowing constructs include typeof, instanceof, equality checks, property checks with in, and checks of discriminant properties. A predicate return type defines a reusable custom guard.

interface Success {
  kind: "success";
  value: string;
}

interface Failure {
  kind: "failure";
  error: Error;
}

type Result = Success | Failure;

function isSuccess(result: Result): result is Success {
  return result.kind === "success";
}

function unwrap(result: Result): string {
  if (isSuccess(result)) return result.value;
  throw result.error;
}

TypeScript trusts the implementation of a user-defined predicate, so an incorrect predicate can make unsafe code appear valid. Prefer direct discriminant checks for simple unions and use runtime validation when values come from untrusted sources.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents