TypeScript by Example

Type Inference

How TypeScript infers types from assignments: const vs let widening, as const, and function return types.

TypeScript infers types from assigned values. Knowing when it widens a type prevents confusing errors later.

const infers a narrow literal type. let widens because the value can change.

const lang = "typescript"; // type: "typescript"
let lang2 = "typescript"; // type: string
 
const count = 42; // type: 42
let count2 = 42; // type: number

Object properties still widen under const because the object is mutable. Use as const when the exact values are the type.

const config = { env: "production", port: 3000 };
// config.env: string
// config.port: number
 
const locked = { env: "production", port: 3000 } as const;
// locked.env: "production"
// locked.port: 3000

Return types are inferred, but explicit annotations document intent and catch accidental changes inside the function body.

function add(a: number, b: number) {
  return a + b;
}
 
function greet(name: string): string {
  return `Hello, ${name}!`;
}

In production

Config objects, route tables, and feature flags often need exact string values. Use as const or an explicit annotation at the source instead of debugging a widened string error far from where the object was created.

Enjoyed this? Get more software craft delivered to your inbox.