Compilation
Compilation
Section titled βCompilationβWhat it means
Section titled βWhat it meansβTypeScript isnβt run directly β itβs compiled (or βtranspiledβ) into plain JavaScript by the TypeScript compiler (tsc), which strips out all the type annotations and interfaces (they exist purely for compile-time checking) and optionally converts newer syntax down to a target JavaScript version the runtime environment supports.
Examples
Section titled βExamplesβinterface User { name: string; age: number;}
function greet(user: User): string { return `Hello, ${user.name}!`;}// output.js (after `tsc`, roughly) -- all type information is gonefunction greet(user) { return `Hello, ${user.name}!`;}tsc input.ts # compile a single filetsc --watch # recompile automatically on savetsc --noEmit # type-check only, don't produce JS outputCommon mistake
Section titled βCommon mistakeβAssuming TypeScriptβs type checking guarantees safety at runtime β types are completely erased during compilation, so if untyped or mistyped data enters your program (e.g. from JSON.parse() or an API response), nothing stops it at runtime even though tsc reported no errors.
interface User { name: string; age: number; }
const response = await fetch("/api/user");const user: User = await response.json(); // TypeScript trusts you here -- no real check!
console.log(user.age.toFixed(2)); // crashes at runtime if the API actually returned age as a stringQuick practice
Section titled βQuick practiceβ-
What happens to TypeScriptβs type annotations when the code is compiled to JavaScript?
Answer
They're completely erased β the compiled JavaScript contains no trace of types, interfaces, or generics. -
What does
tsc --noEmitdo?Answer
Runs type checking without producing any JavaScript output β useful for CI pipelines that just want to verify the code type-checks. -
Why doesnβt TypeScript protect you from bad data returned by
JSON.parse()or afetch()call?Answer
Type annotations are a compile-time-only construct; TypeScript trusts your type assertion but performs no actual runtime validation, so genuinely mismatched data still causes a runtime error.