introduction to typescript
What is TypeScript?
TypeScript is an open-source language developed by Microsoft that builds on top of JavaScript by adding static typing. Every valid JavaScript program is also valid TypeScript — but TypeScript lets you optionally describe the "shape" of your data (numbers, strings, objects, functions) so that mistakes get caught while you're writing code, instead of when your app is already running in a user's browser.
Under the hood, TypeScript code doesn't run directly. It gets compiled (transpiled) into plain JavaScript, which is what actually executes in the browser or on Node.js.
Why Use TypeScript?
- Catches errors early — typos and type mismatches are flagged before you ever run the code.
- Better editor support — autocomplete, inline documentation, and safe refactoring in editors like VS Code.
- Self-documenting code — types describe what a function expects and returns, without needing extra comments.
- Scales well — makes large codebases and teams much easier to manage than plain JavaScript.
- Fully compatible with JavaScript — you can adopt it gradually in an existing JS project.
How TypeScript Works
| Step | What Happens |
|---|---|
| 1. Write | You write code in a .ts file using TypeScript syntax |
| 2. Compile | The TypeScript compiler (tsc) checks types and converts the file into plain .js |
| 3. Run | The resulting JavaScript runs in the browser or Node.js, just like any other JS file |
Installing TypeScript
TypeScript is installed via npm (Node Package Manager):
npm install -g typescriptCheck that it installed correctly:
tsc --versionYour First TypeScript File
Create a file named hello.ts:
function greet(name: string): string {
return "Hello, " + name + "!";
}
console.log(greet("World"));Compile it into JavaScript:
tsc hello.tsThis produces a hello.js file. Run it with Node:
node hello.js
Note:: stringafter the parameter name is a type annotation. It tells TypeScript thatnamemust be a string. If you tried to callgreet(42), TypeScript would immediately flag an error during compilation.
What Happens If You Break the Rules?
function greet(name: string): string {
return "Hello, " + name + "!";
}
greet(42); // Error: Argument of type 'number' is not assignable to parameter of type 'string'.This is the core benefit of TypeScript — it stops this kind of mistake before your code ever runs.
TypeScript vs JavaScript — Quick Comparison
| JavaScript | TypeScript |
|---|---|
| Dynamically typed — types checked at runtime, if at all | Statically typed — types checked at compile time |
| Runs directly in browsers and Node.js | Must be compiled to JavaScript first |
| Errors often appear only when code runs | Many errors are caught while writing code |
.js file extension | .ts file extension |
Coming up next: We'll explore TypeScript's basic types — the building blocks for everything you'll write.