Asserting After Type Guards
What you'll learn: How to use type assertions to specify more precise subtypes even after TypeScript has narrowed a type through runtime checks.
The Core Idea
Sometimes TypeScript's automatic type narrowing gets you close to the type you need, but not quite precise enough. After performing a runtime check (like typeof or instanceof), you might know something more specific about your value than what TypeScript infers. This is where assertions become a helpful precision tool.
Think of it like this: TypeScript sees you check "this is a string," but you happen to know it's not just any string—it's specifically one of three possible values. The runtime check proves it's a string; the assertion tells TypeScript "...and here's the exact flavor of string it is."
When This Pattern Appears
After narrowing with a type guard, TypeScript knows the broader category. But if your application logic guarantees something more specific, you can assert the refined type:
type Status = "pending" | "active" | "complete";
function processValue(value: unknown): Status {
// Type guard narrows to string
if (typeof value === "string") {
// TypeScript knows: value is string
// You know: it's one of three specific strings
return value as Status;
}
return "pending";
}
The typeof guard eliminated all non-string possibilities. The assertion then specifies which strings are valid.
Why Not Just Assert from unknown?
You could jump straight from unknown to Status, but checking with a type guard first adds a layer of runtime safety. The guard confirms the basic shape; the assertion handles the specific subtype:
// Less safe - no runtime validation
const result = value as Status;
// More safe - runtime check + precision assertion
if (typeof value === "string") {
const result = value as Status;
}
Key Takeaway: Type assertions can specify precise subtypes after type guards have validated the broader category, combining runtime safety with compile-time precision.