TypeScript for JavaScript Developers: Getting Started
If you already know JavaScript, TypeScript isn't a new language to learn so much as a type layer on top of what you already know. Here's what actually changes day to day once you add types to a JS codebase.
Basic Types
let age: number = 30;
let name: string = "Alex";
let isActive: boolean = true;
let tags: string[] = ["admin", "editor"];
In most cases, though, you don't need to annotate everything — TypeScript infers types from the value you assign:
let age = 30; // inferred as number, no annotation needed
Interfaces and Type Aliases
Describing the shape of an object is where TypeScript starts paying off immediately:
interface User {
id: number;
name: string;
email?: string; // optional
}
function greet(user: User) {
console.log(`Hello, ${user.name}`);
}
Now calling greet({ id: 1 }) fails at compile time instead of printing "Hello, undefined" in production.
Union Types
Union types model values that can be one of several specific shapes, which is especially useful for state:
type RequestState =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: User[] }
| { status: "error"; message: string };
Combined with a switch on status, TypeScript narrows the type inside each branch, so data is only accessible where status === "success".
Generics
Generics let you write reusable code that still keeps type information instead of falling back to any:
function firstOf<T>(items: T[]): T | undefined {
return items[0];
}
const firstUser = firstOf(users); // typed as User | undefined
Avoiding the any Escape Hatch
any turns off type checking for that value entirely, which quietly reintroduces every bug TypeScript exists to prevent. When the real type is genuinely unknown (parsing external JSON, say), prefer unknown and narrow it with a type guard before using it:
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null && "id" in value;
}
Migrating an Existing JS Project
- Rename files incrementally from
.jsto.ts— you don't need to convert everything at once. - Start with
"strict": falseif the codebase is large, then tighten flags likestrictNullChecksonce the obvious errors are cleared. - Add types to function boundaries (parameters and return values) first — that's where type safety catches the most real bugs.
Summary
TypeScript's value isn't in the annotations themselves, it's in catching the class of bugs that come from calling something with the wrong shape of data — which, in most real codebases, is a lot of bugs. Start at function boundaries and object shapes, and let inference handle the rest.
