TypeScript Fundamentals
TypeScript Mental Model
TypeScript is a static typechecker for JavaScript. It analyzes your code before runtime, reports likely type mistakes, and then emits JavaScript; its types do not exist unless you also write runtime checks.
- TypeScript checks programs; JavaScript runs programs
- Types are erased
- Assertions are not validation
- Unknown data should enter as
unknown - TypeScript works best with strict project settings
type User = { id: string; name: string }
const raw = await response.json()
const user1 = raw as User
// Compiler is quiet, but runtime value may be anything.
const user2 = parseUser(raw)
// Runtime validation proves the shape before returning User.| Can help with | Cannot prove by itself |
|---|---|
| Internal function calls | External API response shape |
| Property names and return types | Database contents are valid |
| Exhaustive union handling | User input follows schema |
| Refactoring confidence | Runtime environment has required APIs |
| Library API contracts | Declaration files match implementation |