Quick Overview
`let x = "GET"` infers `string` because the binding can change; `const x = "GET"` infers the literal `"GET"`. That widening rule is why object properties need `as const` to stay narrow.
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!
TypeScript erases entirely at build time, so a `string` annotation produces no runtime check whatsoever. A value arriving from an API is whatever the server actually sent, regardless of what the annotation claims.
`string[]` is any number of strings; `[string, number]` is exactly two, in that order. `readonly` removes the mutating methods at compile time, so `push` becomes a type error rather than a runtime surprise.
`?` makes a property optional, which adds `undefined` to its type rather than removing the key. That is why reading it still needs a check even after the shape is declared.
Average 5.0 by 1 learner