Type guards
suggest changeBuilt-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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents