TypeScript for JavaScript Developers: The Essentials
TypeScript is JavaScript with types. The types are checked at build time and then removed, so the code that runs is plain JavaScript. What you gain is autocomplete that knows your data and errors before your users find them.
Inference does most of the work
let count = 0; // number
const name = 'Asha'; // 'Asha' (a literal type, since it's const)
const tags = ['a', 'b']; // string[]
count = 'ten'; // Error: Type 'string' is not assignable to type 'number'
Annotate function parameters and public APIs; let TypeScript infer the rest.
Objects: interface or type
interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date;
}
type Status = 'active' | 'suspended' | 'deleted'; // union of literals
type Account = User & { status: Status }; // intersection
Both describe object shapes. Use interface for objects you might extend, and type for unions, tuples and computed types. Consistency within a project matters more than the choice.
Functions
function formatPrice(amount: number, currency = 'INR'): string {
return new Intl.NumberFormat('en-IN', { style: 'currency', currency }).format(amount);
}
const isAdult = (age: number): boolean => age >= 18;
async function getUser(id: number): Promise<User | null> {
const res = await fetch(`/api/users/${id}`);
return res.ok ? res.json() : null;
}
Arrays, tuples and records
const ids: number[] = [1, 2, 3];
const point: [number, number] = [10, 20];
const scores: Record<string, number> = { asha: 90, ravi: 85 };
Getting started in an existing project
- Add
typescriptand atsconfig.jsonwith"allowJs": true. - Rename files from
.jsto.tsone at a time, starting with utilities. - Turn on
"strict": trueas early as you can; it catches the most bugs.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.