Discover how TypeScript infers types automatically and how let versus const declarations shape wide types versus narrow literal types.
Master typed array lists, fixed-length tuples, and readonly modifiers to enforce immutable data structures in TypeScript.
You do not need to annotate every variable manually. TypeScript features a powerful Type Inference Engine that inspects initial values and automatically assigns the narrowest possible type.
Notice how TypeScript infers types differently depending on whether you declare a variable with let or const:
// Infered as wide 'string' type (because 'let' can be reassigned later)
let role = "admin"; // Type: string
role = "editor"; // Valid!
// Inferred as narrow Literal Type 'admin' (because 'const' can NEVER change)
const primaryRole = "admin"; // Type: "admin"
// primaryRole = "editor"; // Error: Cannot assign to 'primaryRole'
A Literal Type is a type that represents an exact single value (like the string "admin" or the number 404), rather than any arbitrary string or number:
type HTTPSuccessCode = 200 | 201; // Literal union type
const currentStatus: HTTPSuccessCode = 200; // Valid
// const badStatus: HTTPSuccessCode = 500; // Error: Type 500 is not assignable to 200 | 201
[ Wide Type ] ──> string
│ (Narrows down)
▼
[ Literal Type ] ──> "admin" | "editor" | "viewer"
let name: string = "Alex" is redundant because TypeScript already infers string from "Alex".as const or explicit literal types.Rely on inference for simple initializations. Next, let me introduce TypeScript Arrays, Tuples, and Readonly modifiers!