TypeScript Introduction
TypeScript Introduction: Static Types on Top of JavaScript
TypeScript is an open-source, statically typed superset of JavaScript built by Microsoft. Every valid JavaScript file is valid TypeScript, and TypeScript adds compile-time type annotations that disappear once code compiles down to plain JavaScript.
Instead of waiting for a browser crash or production TypeError when an API field is missing, TypeScript flags mismatched types directly inside your editor as you type.
How TypeScript Compiles to JavaScript
flowchart LR
A["Source (.ts / .tsx)"] --> B["Type Checker (tsc)"]
B -- "Errors" --> C["Editor & CLI Diagnostics"]
B -- "Valid" --> D["Emitted JavaScript (.js)"]
The TypeScript compiler (tsc) checks variable types, function arguments, and object shapes, then strips away all type syntax to emit clean ES modules or CommonJS output for browsers and Node.js.
Your First Typed Example
Notice how : number and the Invoice interface catch accidental string typos before the code ever runs.
interface Invoice {
id: number;
total: number;
paid: boolean;
}
function formatTotal(invoice: Invoice): string {
const status = invoice.paid ? "PAID" : "DUE";
return `Invoice #${invoice.id}: $${invoice.total.toFixed(2)} (${status})`;
}
console.log(formatTotal({ id: 104, total: 89.5, paid: true }));
Common Mistakes to Avoid
- Expecting TypeScript types to validate JSON at runtime: Types vanish during compilation, so validate untrusted API or form payloads at runtime with libraries like Zod.
- Disabling strict checks in
tsconfig.json: Turning off"strict": trueallows silentanyandnullbugs that defeat the purpose of TypeScript. - Over-annotating obvious variables: Let TypeScript infer simple constants like
const port = 3000instead of adding redundant types everywhere.
Frequently Asked Questions
Do browsers run .ts files directly?
No. Browsers only execute JavaScript, so a build tool like tsc, Vite, esbuild, or Next.js compiles your TypeScript into .js first (though modern Node.js 22+ can strip simple types directly).
Does TypeScript add performance overhead at runtime?
Zero. Type annotations are erased completely at compile time, leaving standard JavaScript execution speed.
Should beginners learn JavaScript before TypeScript?
Learning core JavaScript variables, arrays, objects, promises, and functions first makes TypeScript far easier because TypeScript builds directly on JavaScript semantics.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.