~/
hackweb.dev
TypeScript Basics & Setup
Quiz
⌘K
...
~/
/tutorials
/ts/ts-basic-setup/edit
~ Contribute
Suggest a correction or improvement. The author reviews it before it goes live.
Loading...
Comment
0 / 300
Typo
Grammar
Broken link
Clarify
Code
en/tutorials/ts/1ts-basic-setup
Write
Preview
Diff
# TypeScript Basics & Setup TypeScript is a superset of JavaScript that adds static typing. It catches errors before your code runs. ## What Is TypeScript? TypeScript extends JavaScript with type annotations checked at compile time. It compiles to plain JavaScript. ```typescript // JavaScript - errors appear at runtime let name = "John"; name = 42; // No error, but breaks later // TypeScript - errors caught at compile time let name: string = "John"; name = 42; // Error: Type 'number' is not assignable to type 'string' ``` **Why TypeScript?** Catches bugs early, adds autocomplete, and makes code self-documenting. ## Installing TypeScript ```bash # Global install npm install -g typescript # Or as a dev dependency npm install --save-dev typescript ``` **Tip:** Local installation keeps versions pinned per project. ## Compiling TypeScript The `tsc` compiler converts `.ts` files to `.js`: ```bash tsc app.ts # Compile a single file tsc # Compile using tsconfig.json ``` ## tsconfig.json Configure how TypeScript compiles your project: ```json { "compilerOptions": { "target": "ES2020", "module": "commonjs", "strict": true, "outDir": "./dist", "rootDir": "./src", "esModuleInterop": true }, "include": ["src/**/*"], "exclude": ["node_modules"] } ``` **Key options:** `target` = JS version output, `strict` = strict type-checking, `outDir` = output folder. ## @types Packages JavaScript libraries without built-in types need `@types` packages: ```bash npm install express @types/express npm install react react-dom @types/react @types/react-dom ``` **Remember:** `@types` provides type definitions for libraries that don't ship their own. ## Best Practices - Enable `strict` mode in tsconfig - Use `ES2020` or later as target - Install `@types` for third-party libraries - Start simple, add strictness gradually ## Common Mistakes - Not installing `@types` packages - Setting `target` too old - Running `.ts` files directly instead of compiling first - Ignoring TypeScript errors - Using `any` excessively
No changes yet
Reset to original
Submit suggestion
cancel