TypeScript Documentation
JavaScript with types — catch bugs before running your code and get great editor autocomplete.
TypeScript (TS) is JavaScript with static types. You write .ts files, the TypeScript compiler checks them for type errors and outputs plain JavaScript. Types catch bugs before your code runs and give your editor great autocomplete — which is why most large React, Angular and Node.js projects use TypeScript.
1. Introduction & Installation
Install Node.js first, then TypeScript:
npm install -g typescript # gives the tsc compiler
tsc --version
tsc --init # creates tsconfig.json
tsc app.ts && node app.js # compile, then run the JavaScript
npx tsx app.ts # or run .ts directly (no separate build step)
// app.ts
const message: string = "Hello, Codify!";
console.log(message);
Output:
Hello, Codify!
New projects: npm create vite@latest my-app -- --template react-ts sets up React + TypeScript.
⚠️ Common error:
'tsc' is not recognized— the global npm bin folder is not on PATH. Usenpx tscinstead.
2. Basic Syntax
TypeScript syntax is JavaScript syntax plus type annotations after a colon: name: type. Types are erased when compiling — they cost nothing at runtime.
function greet(name: string, times: number = 1): string {
return `Hello ${name}! `.repeat(times).trim();
}
let score: number = 90;
const tags: string[] = ["ts", "js"];
console.log(greet("Asha", 2), score + 5, tags.length);
Output:
Hello Asha! Hello Asha! 95 2
TypeScript infers types when it can: let count = 0 is already a number, so you don't need to annotate everything.
⚠️ Common error:
Argument of type 'string' is not assignable to parameter of type 'number'.— TypeScript caught a wrong argument before running. Fix the value or the type.
3. Variables & Data Types
| Type | Example |
|---|---|
string, number, boolean, bigint |
let n: number = 5; |
| arrays | number[] or Array<number> |
| tuples | [string, number] |
null, undefined |
`let x: string |
any |
turns type checking off (avoid) |
unknown |
safe "anything" — must be checked before use |
never |
a value that never occurs (e.g. a function that always throws) |
void |
function returns nothing |
| literal types | `"GET" |
let id: number = 101;
let username: string = "ravi_dev";
let verified: boolean = false;
const scores: number[] = [88, 92, 79];
const entry: [string, number] = ["maths", 95]; // tuple
let method: "GET" | "POST" = "GET"; // literal union
let input: unknown = "42";
if (typeof input === "string") console.log(input.toUpperCase());
enum Role { User = "USER", Admin = "ADMIN" }
const me = { id, username, verified, role: Role.Admin };
console.log(me, scores.length, entry[0], method);
Output:
42
{ id: 101, username: 'ravi_dev', verified: false, role: 'ADMIN' } 3 maths GET
⚠️ Common error: using
anyeverywhere — it silently disables all checks. Preferunknownand narrow it.
4. Operators
All JavaScript operators work the same (+ - * / % **, === !==, && || ??, ?., spread ...). TypeScript adds type-level operators:
| Operator | Meaning |
|---|---|
x! |
non-null assertion — "trust me, it's not null" |
x as T |
type assertion |
keyof T |
union of T's keys |
typeof value |
(in a type position) the type of a value |
T[K] |
indexed access type |
satisfies T |
check a value matches a type without widening it |
const config = { port: 5000, host: "localhost" };
type Config = typeof config; // { port: number; host: string }
type ConfigKey = keyof Config; // "port" | "host"
function read(key: ConfigKey): Config[ConfigKey] {
return config[key];
}
const maybe: string | undefined = process.env.NO_SUCH_VAR;
console.log(read("port"), read("host"), maybe ?? "default", (maybe?.length ?? 0) + 1);
Output:
5000 localhost default 1
⚠️ Common error: overusing
!andas— they silence the compiler; if you're wrong, the bug appears at runtime.
5. Conditional Statements
if, else, switch and ?: work like JavaScript. TypeScript narrows types inside conditions, and can check that a switch handles every case (exhaustiveness):
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.PI * s.radius ** 2; // s is the circle type here
case "rect":
return s.width * s.height; // s is the rect type here
default: {
const unreachable: never = s; // error if a new kind is not handled
return unreachable;
}
}
}
console.log(area({ kind: "rect", width: 3, height: 4 }), area({ kind: "circle", radius: 1 }).toFixed(2));
Output:
12 3.14
⚠️ Common error:
Property 'radius' does not exist on type 'Shape'— you accessed a member before narrowing. Checks.kindfirst.
6. Loops
Loops are the same as JavaScript; TypeScript types the loop variables for you.
const prices: Record<string, number> = { pen: 10, book: 250, bag: 900 };
let total = 0;
for (const [item, price] of Object.entries(prices)) {
total += price;
console.log(`${item.padEnd(5)} ${price}`);
}
console.log("total", total);
const matrix: number[][] = [[1, 2], [3, 4]];
for (let i = 0; i < matrix.length; i++) {
for (const value of matrix[i]) process.stdout.write(value * 10 + " ");
}
console.log();
Output:
pen 10
book 250
bag 900
total 1160
10 20 30 40
⚠️ Common error: with
noUncheckedIndexedAccesson,arr[i]has typeT | undefined— handle the undefined case or usefor...of.
7. Functions
// optional (?) and default parameters, explicit return type
function formatPrice(amount: number, currency: string = "INR", decimals?: number): string {
return `${currency} ${amount.toFixed(decimals ?? 2)}`;
}
// function type alias
type Comparator<T> = (a: T, b: T) => number;
const byLength: Comparator<string> = (a, b) => a.length - b.length;
// overloads: different signatures, one implementation
function toArray(x: string): string[];
function toArray(x: number): number[];
function toArray(x: string | number): (string | number)[] {
return [x];
}
// rest parameters
const sum = (...nums: number[]): number => nums.reduce((s, n) => s + n, 0);
console.log(formatPrice(49.5), formatPrice(10, "USD", 0));
console.log(["kiwi", "fig", "banana"].sort(byLength), toArray(5), sum(1, 2, 3));
Output:
INR 49.50 USD 10
[ 'fig', 'kiwi', 'banana' ] [ 5 ] 6
⚠️ Common error:
Not all code paths return a value— with an explicit return type, every branch must return.
8. Arrays & Data Structures
Interfaces and type aliases describe the shape of objects:
interface Student {
readonly id: number; // can't be changed after creation
name: string;
marks: number[];
email?: string; // optional
}
type Grade = "A" | "B" | "C";
const students: Student[] = [
{ id: 1, name: "Asha", marks: [91, 88] },
{ id: 2, name: "Ravi", marks: [72, 65], email: "ravi@example.com" },
];
const avg = (s: Student): number => s.marks.reduce((a, b) => a + b, 0) / s.marks.length;
const grade = (score: number): Grade => (score >= 85 ? "A" : score >= 70 ? "B" : "C");
const report = new Map<string, Grade>();
for (const s of students) report.set(s.name, grade(avg(s)));
console.log(report, students.filter((s) => s.email).map((s) => s.name));
const unique = new Set<number>([3, 1, 3, 2]);
const lookup: Record<number, string> = { 200: "OK", 404: "Not Found" };
console.log([...unique].sort(), lookup[404]);
Output:
Map(2) { 'Asha' => 'A', 'Ravi' => 'C' } [ 'Ravi' ]
[ 1, 2, 3 ] Not Found
interface vs type: both describe objects; interfaces can be extended/merged, type can also express unions, tuples and mapped types.
⚠️ Common error:
Property 'email' is missing— required properties must be provided. Mark it optional with?if it really is optional.
9. Object-Oriented Programming
interface Payable {
pay(amount: number): string;
}
abstract class Employee implements Payable {
private static nextId = 1;
readonly id: number;
constructor(public name: string, protected salary: number) { // parameter properties
this.id = Employee.nextId++;
}
abstract role(): string;
pay(amount: number): string {
return `${this.name} (${this.role()}) paid ${amount}`;
}
}
class Developer extends Employee {
constructor(name: string, salary: number, private stack: string[]) {
super(name, salary);
}
role(): string {
return `dev: ${this.stack.join("/")}`;
}
raise(pct: number): number {
this.salary += (this.salary * pct) / 100;
return this.salary;
}
}
const dev = new Developer("Neha", 80000, ["react", "node"]);
console.log(dev.pay(5000), dev.id, dev.raise(10));
Output:
Neha (dev: react/node) paid 5000 1 88000
Access modifiers: public (default), private (class only — compile-time), protected (class + subclasses), readonly. For runtime privacy use JavaScript's #field.
⚠️ Common error:
Property 'salary' is protected and only accessible within class 'Employee' and its subclasses— you accessed it from outside.
10. Advanced Concepts
Generics — reusable code that keeps type information:
function first<T>(items: T[]): T | undefined {
return items[0];
}
interface ApiResponse<T> {
ok: boolean;
data: T;
}
function wrap<T>(data: T): ApiResponse<T> {
return { ok: true, data };
}
function longest<T extends { length: number }>(a: T, b: T): T { // constraint
return a.length >= b.length ? a : b;
}
const res = wrap({ id: 7, title: "Learn generics" });
console.log(first([10, 20]), res.data.title, longest("hello", "hi"), longest([1, 2], [1, 2, 3]));
10 Learn generics hello [ 1, 2, 3 ]
Utility types transform existing types:
interface User {
id: number;
name: string;
email: string;
password: string;
}
type PublicUser = Omit<User, "password">; // remove keys
type UserUpdate = Partial<Pick<User, "name" | "email">>; // pick + make optional
type Roles = Record<"admin" | "user", string[]>;
const pub: PublicUser = { id: 1, name: "Asha", email: "asha@example.com" };
const patch: UserUpdate = { name: "Asha R." };
const roles: Roles = { admin: ["delete"], user: ["read"] };
type Fetcher = () => Promise<User>;
type FetchedUser = Awaited<ReturnType<Fetcher>>; // User
const check: Readonly<FetchedUser> = { ...pub, password: "x" };
console.log(Object.keys(pub).length, patch, roles.admin[0], check.name);
3 { name: 'Asha R.' } delete Asha
Type guards narrow unknown data (e.g. JSON from an API):
interface Product { name: string; price: number }
function isProduct(x: unknown): x is Product {
return typeof x === "object" && x !== null && "name" in x && "price" in x &&
typeof (x as Product).price === "number";
}
const raw: unknown = JSON.parse('{"name":"Keyboard","price":1499}');
if (isProduct(raw)) console.log(`${raw.name}: ₹${raw.price}`);
else console.log("invalid product");
Keyboard: ₹1499
TypeScript with React — type your props and state:
type ButtonProps = { label: string; onClick: () => void; variant?: "primary" | "ghost" };
export function Button({ label, onClick, variant = "primary" }: ButtonProps) {
return <button className={variant} onClick={onClick}>{label}</button>;
}
const [count, setCount] = useState<number>(0);
const [user, setUser] = useState<User | null>(null);
Also learn: tsconfig.json (strict: true — always), declaration files (.d.ts, @types/* packages), mapped and conditional types, as const, and satisfies.
11. Examples with Output
Example 1 — A typed stack class
class Stack<T> {
private items: T[] = [];
push(x: T): void { this.items.push(x); }
pop(): T | undefined { return this.items.pop(); }
peek(): T | undefined { return this.items[this.items.length - 1]; }
get size(): number { return this.items.length; }
}
const s = new Stack<string>();
s.push("a"); s.push("b"); s.push("c");
console.log(s.pop(), s.peek(), s.size);
c b 2
Example 2 — Typed reducer (like React's useReducer)
type State = { count: number };
type Action = { type: "inc" } | { type: "dec" } | { type: "set"; value: number };
function reducer(state: State, action: Action): State {
switch (action.type) {
case "inc": return { count: state.count + 1 };
case "dec": return { count: state.count - 1 };
case "set": return { count: action.value };
}
}
const actions: Action[] = [{ type: "inc" }, { type: "inc" }, { type: "set", value: 10 }, { type: "dec" }];
console.log(actions.reduce(reducer, { count: 0 }));
{ count: 9 }
Example 3 — Group by a key with generics
function groupBy<T, K extends PropertyKey>(items: T[], key: (item: T) => K): Record<K, T[]> {
return items.reduce((acc, item) => {
(acc[key(item)] ||= []).push(item);
return acc;
}, {} as Record<K, T[]>);
}
const words = ["apple", "avocado", "banana", "blueberry", "cherry"];
console.log(groupBy(words, (w) => w[0]));
{
a: [ 'apple', 'avocado' ],
b: [ 'banana', 'blueberry' ],
c: [ 'cherry' ]
}
12. Practice Problems
TypeScript runs wherever JavaScript does — practise the algorithms in JavaScript on Codify and add types in your own projects:
- Type a function
average(nums: number[]): numberthat returns0for an empty array. - Write an interface for a
BlogPost(id, title, tags, optionalpublishedAt: Date) and a function that returns only published posts. - Implement a generic
Queue<T>class withenqueue,dequeueandsize. - Write
pluck<T, K extends keyof T>(items: T[], key: K): T[K][]. - Model API responses as a discriminated union:
{ status: "loading" } | { status: "error"; message: string } | { status: "success"; data: T }, and render each case. - Convert a small JavaScript project (e.g. a to-do app) to TypeScript with
strict: true. - Algorithms in JS/TS: Two Sum, Valid Parentheses, Binary Search.
13. Interview Questions
1. What is TypeScript and why use it? A typed superset of JavaScript that compiles to JS. It catches type errors at compile time, improves tooling (autocomplete, refactoring) and documents code.
2. interface vs type?
Both describe object shapes. Interfaces can be extended and merged (declaration merging); type aliases can also represent unions, tuples, primitives and mapped/conditional types.
3. any vs unknown?
any disables type checking. unknown accepts any value but must be narrowed (e.g. typeof x === "string") before use — the safe choice.
4. What are generics?
Type parameters (<T>) that let functions/classes work with many types while keeping type safety, e.g. function first<T>(a: T[]): T.
5. What is type narrowing?
Refining a broad type to a specific one inside a branch using typeof, instanceof, in, equality checks, discriminant properties or custom type guards (x is T).
6. What is a discriminated union?
A union of object types sharing a literal "tag" property (kind: "circle" | "rect"), so a switch on the tag narrows to the right member.
7. Name some utility types.
Partial, Required, Readonly, Pick, Omit, Record, ReturnType, Parameters, Awaited, NonNullable.
8. Does TypeScript run in the browser? No — it is compiled (types erased) to JavaScript, which the browser runs. Types don't exist at runtime.
9. What does strict mode enable?
A group of checks including strictNullChecks, noImplicitAny and strictFunctionTypes — recommended for all projects.
10. What is never?
The type with no values — return type of functions that always throw or loop forever, and the type left after exhaustive narrowing.
14. Cheat Sheet & References
Basic types
let n: number = 1; let s: string = "a"; let ok: boolean = true;
let arr: number[] = [1, 2]; let tup: [string, number] = ["a", 1];
let id: string | number; let dir: "up" | "down" = "up";
let data: unknown; let nothing: void; let x: any;
Objects
interface User { id: number; name: string; email?: string; readonly createdAt: Date; }
type Point = { x: number; y: number };
interface Admin extends User { permissions: string[]; }
type Dict = Record<string, number>;
Functions
function add(a: number, b = 0): number { return a + b; }
const greet = (name?: string): string => `Hi ${name ?? "there"}`;
type Handler = (event: MouseEvent) => void;
function first<T>(items: T[]): T | undefined { return items[0]; }
Classes
class Car { constructor(public brand: string, private speed = 0) {} }
abstract class Shape { abstract area(): number; }
class Sq extends Shape implements Comparable { area() { return 1; } }
Narrowing and assertions
if (typeof v === "string") { } if (v instanceof Date) { } if ("id" in obj) { }
function isUser(x: unknown): x is User { return typeof x === "object" && x !== null; }
const el = document.getElementById("app") as HTMLDivElement;
const cfg = { mode: "dark" } as const;
Utility types
Partial<User>; Required<User>; Readonly<User>;
Pick<User, "id" | "name">; Omit<User, "email">;
ReturnType<typeof fn>; Parameters<typeof fn>; Awaited<Promise<T>>;
keyof User; User["name"]; NonNullable<string | null>;
tsconfig essentials
{ "compilerOptions": { "strict": true, "target": "ES2022", "module": "ESNext", "jsx": "react-jsx" } }
Official documentation