TypeScriptIntermediate 6 min read
TypeScript for JavaScript Developers: The Easy Introduction
TypeScript is JavaScript with types. It catches mistakes while you type, before your users ever see them, and makes big codebases much easier to work in.
By Learn Refill Mentors · Updated
Why learn TypeScript?
- Catches bugs before the code runs
- Better autocomplete in your editor
- Most modern companies use it with React and Node
1Add types to variables
Write the type after a colon. TypeScript will warn you if the value doesn't match.
TypeScript
let age: number = 21;
let name: string = "Aman";
let isActive: boolean = true;2Type your functions
Type the inputs and the return value so every call is checked.
TypeScript
function total(price: number, qty: number): number {
return price * qty;
}
total(499, 2); // ok
// total("499", 2); // error3Describe objects with interfaces
An interface is a shape for an object. Use ? for optional fields.
TypeScript
interface Student {
name: string;
course: string;
phone?: string;
}
const s: Student = { name: "Riya", course: "MERN" };4Union types for fixed choices
Limit a value to a set of allowed options.
TypeScript
type Plan = "monthly" | "one-time";
let plan: Plan = "monthly";5Generics for reusable code
Generics let one function work with many types while staying type-safe.
TypeScript
function first<T>(items: T[]): T {
return items[0];
}
first<string>(["React", "Next.js"]);Common mistakes
- Using any everywhere — it turns type checking off
- Fighting the compiler instead of reading the error message
Practice task
Convert your JavaScript to-do app to TypeScript with a Todo interface and typed functions.
Frequently asked questions
Do I need to learn JavaScript before TypeScript?
Yes. TypeScript is JavaScript plus types, so JS basics come first.