3. TypeScript Fundamentals & Type Thinking
Why TypeScript? Type Inference, unknown vs any & strict Mode
Eliminate 'Cannot read properties of undefined' bugs before code runs: master TypeScript's structural type system, inference, tuples/readonly, unknown vs any, and tsconfig strict mode.
- Explain how TypeScript checks types at compile time and erases them into clean JavaScript
- Rely on TypeScript type inference instead of redundant annotations
- Choose safe `unknown` (with narrowing) over dangerous `any` for untrusted API/JSON inputs
In plain JavaScript, misspelling user.emial or passing a string "42" where a number is expected silently passes until a user triggers that exact button in production and hits Cannot read properties of undefined.
TypeScript is JavaScript plus a compile-time type checker. It catches typos, missing null/undefined checks, and mismatched API payloads right inside your editor—before your browser ever loads a line of code!
1. Compile-Time Safety, Zero Runtime Overhead
unknown + strict checks
Catches null & typo bugs
Types erased for browser
Type annotations are checked by tsc / your editor before code runs, then completely erased into clean JavaScript.
TypeScript annotations (: string, : number) do not slow down your app at runtime. During your build step (tsc or Vite), TypeScript verifies every type contract and erases all type syntax, emitting plain fast JavaScript.
2. Inference vs Explicit Annotations
You do not need to annotate every variable—TypeScript infers types automatically whenever you initialize a value:
// Redundant: TypeScript already knows score is number and tags is string[]
const score: number = 95;
// Idiomatic: let inference work for local variables; annotate function params & returns!
const score = 95;
const tags = ["ts", "web"]; // inferred as string[]
function formatTotal(price: number, qty: number): string {
return "$" + (price * qty).toFixed(2);
}Everyday Type Building Blocks
- Primitives:
string,number,boolean,null,undefined - Arrays & Tuples:
string[]vs fixed-length[number, number]([lat, lon]) readonly:readonly string[]or{ readonly id: string; title: string }prevents accidental.push()or reassignment at compile time!
3. Why unknown Beats any Every Time
When reading JSON.parse(raw) or an external API response, you don't know its exact shape yet:
anyturns off TypeScript completely—lettingdata.nonExistent.boom()compile with zero warnings!unknownis the type-safe top type: TypeScript accepts any value intounknown, but refuses to let you access properties or call methods until you verify its shape at runtime!
function parseMessage(input: unknown): string {
// input.toUpperCase(); -> Compile Error! Object is of type 'unknown'
if (typeof input === "string") {
return input.trim().toUpperCase(); // Safe! Narrowed to string
}
return "INVALID";
}"strict": true enables strictNullChecks (preventing null/undefined crashes) and noImplicitAny (catching untyped parameters). Starting every new TypeScript project with "strict": true saves hundreds of hours of debugging later.
Try It Yourself in the Playground
Since TypeScript types are erased at runtime, unknown-style runtime guards are what actually protect your app against malformed JSON.parse() payloads! Test a strict runtime parser below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why does JSON.parse(text) return any in TypeScript's default standard library, and how can you make parsing safer?
Quick Checkpoints
What is the crucial safety difference between any and unknown in TypeScript?
What happens to TypeScript type annotations (: string, interface User) after tsc or Vite builds your project for the browser?