Getting Started with TypeScript
A practical introduction to TypeScript for developers coming from JavaScript.
If you've been writing JavaScript and keep running into bugs that type checking could have caught, TypeScript is worth your time.
What Is TypeScript?
TypeScript is JavaScript with types. It adds a type system that catches errors at compile time instead of runtime. You write TypeScript, it compiles to JavaScript, and you run it like normal.
Why Use It?
The biggest benefit is catching bugs early. Here's a common JavaScript mistake:
function add(a, b) {
return a + b;
}
add("1", 2); // "12" — not what we wanted
With TypeScript:
function add(a: number, b: number): number {
return a + b;
}
add("1", 2); // Type error!
Getting Started
The easiest way to start is to install TypeScript in your project:
npm install --save-dev typescript
Then create a tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"strict": true,
"moduleResolution": "bundler"
}
}
The Basics
Here are the core types you'll use every day:
// Primitives
let name: string = "Alice";
let age: number = 30;
let active: boolean = true;
// Arrays
let tags: string[] = ["dev", "blog"];
// Objects
let user: { name: string; age: number } = {
name: "Alice",
age: 30,
};
Interfaces
Once you start defining object shapes repeatedly, use interfaces:
interface User {
name: string;
age: number;
email?: string; // optional
}
function greet(user: User) {
return `Hello, ${user.name}`;
}
Tips
- Start with
strict: true— it's more work upfront but catches more bugs - Use type inference — don't annotate everything; let TypeScript figure it out when it can
- Gradual adoption — you can rename
.jsfiles to.tsone at a time
TypeScript has a learning curve, but once you get comfortable with it, going back to plain JavaScript feels risky.
Comments
Loading comments...