🔷 TypeScript
TypeScript Type Inference: When to Annotate and When Not To
TypeScript infers most types automatically. Here's when you need annotations and when they just add noise.
Examifyr·2026·4 min read
What TypeScript infers
TypeScript automatically infers types from assignments, return values, and context.
// No annotation needed — TypeScript infers these:
const name = "Alice"; // type: string
const age = 30; // type: number
const active = true; // type: boolean
const scores = [90, 78, 85]; // type: number[]
// Function return types are inferred
function add(a: number, b: number) {
return a + b; // return type: number (inferred)
}
// Object shape is inferred
const user = { name: "Alice", role: "admin" };
// type: { name: string; role: string }When to add explicit annotations
Annotations are most useful when TypeScript can't infer, or when you want to document intent.
// 1. Function parameters (TypeScript can't infer these)
function greet(name: string): string {
return `Hello, ${name}`;
}
// 2. Variables initialised to null/undefined
let user: User | null = null;
// 3. Complex return types for documentation
function fetchUsers(): Promise<User[]> {
return fetch('/api/users').then(r => r.json());
}
// 4. When inference is too wide
const status = "active"; // type: string
const status: Status = "active"; // type: Status (literal)Widening and narrowing
TypeScript may infer a wider type than you want. Use explicit types or const assertions to narrow.
// Widening: TypeScript infers string, not the literal
let direction = "north"; // type: string
const direction = "north"; // type: "north" (literal — const doesn't widen)
// Const assertion
const config = {
endpoint: "/api",
method: "GET",
} as const;
// type: { readonly endpoint: "/api"; readonly method: "GET" }
// Without as const: { endpoint: string; method: string }
// Useful for union types from arrays
const ROLES = ["admin", "user", "guest"] as const;
type Role = typeof ROLES[number]; // "admin" | "user" | "guest"Note: as const is very useful for creating union types from arrays — a common TypeScript pattern.
Exam tip
Know when NOT to annotate: TypeScript can infer return types, variable types from assignments, and array element types. Over-annotation is noise. DO annotate function parameters, complex return types, and nullable variables.
🎯
Think you're ready? Prove it.
Take the free TypeScript readiness test. Get a score, topic breakdown, and your exact weak areas.
Take the free TypeScript test →Free · No sign-up · Instant results