CPCODELAB
TypeScript

Type Inference

6 min read

Type Inference

TypeScript infers types automatically when you provide an initial value. You rarely need to annotate local variables — the compiler figures out the type from context.

ts
// All inferred — no explicit annotations needed
const count = 0;              // number
const items = ["a", "b"];     // string[]
const map = new Map<string, number>(); // Map<string, number>

// Inferred return type
function square(n: number) {
  return n * n; // inferred return type: number
}

// Contextual typing
const nums = [1, 2, 3];
nums.forEach((n) => {
  console.log(n.toFixed(2)); // n is inferred as number
});

Widening is when TypeScript infers a broader type than you might expect. A let variable initialized to "hello" gets type string, not "hello". A const variable gets the literal type "hello" because it can never change.

ts
let mutable = "hello";  // type: string (widened)
const fixed = "hello";  // type: "hello" (literal)

// Use 'as const' to get a literal type from an object or array
const config = { env: "production", port: 3000 } as const;
// config.env: "production"  config.port: 3000
Ready to test yourself?
Practice TypeScript— quiz & coding exercises