Course contentsShow
← TypeScript
Lesson 162 of 1,7964. Type InferenceFree lesson

Annotating to Enforce Constraints

Using explicit annotations to prevent accidentally widening types and enforce stricter contracts than inference provides.

Annotating to Enforce Constraints

What you'll learn: How to use explicit type annotations to prevent TypeScript from widening types too much and to enforce stricter contracts than inference would provide on its own.

The Problem with Pure Inference

TypeScript's inference is smart, but sometimes too helpful. When you let TypeScript infer types, it often widens them to be more flexible than you actually want. This is great for general code, but sometimes you need to lock things down tighter.

Using Annotations as Safety Rails

Think of type annotations like guardrails on a mountain road. Inference might say "this variable could be any string," but your application logic requires it to be specifically "active", "pending", or "closed". By explicitly annotating, you tell TypeScript: "Don't let me accidentally assign anything else."

// Inference widens to string
let status = "active"; // type: string
status = "unknown"; // TypeScript allows this!

// Annotation enforces constraints
let statusConstrained: "active" | "pending" | "closed" = "active";
statusConstrained = "unknown"; // Error: Type '"unknown"' is not assignable

When to Use Constraint Annotations

Use explicit annotations when:

  • You need exact literal types, not widened primitives
  • Function parameters must accept only specific values
  • Object properties should remain narrow
  • You're defining a contract that inference alone won't maintain
function setStatus(status: "active" | "pending" | "closed") {
  // Parameter annotation ensures only valid statuses
}

setStatus("active");   // ✓
setStatus("unknown");  // Error

Key Takeaway: While inference is convenient, explicit type annotations let you enforce stricter constraints than TypeScript would infer, preventing bugs from accidentally widened types and making your code's contracts crystal clear.