Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Guides › TypeScript & Modern JavaScript

TypeScript: Complete Beginner to Advanced Guide

Learn TypeScript from scratch with types, interfaces, generics, narrowing, utility types, modules, configuration, and real-world examples.

TypeScript: Complete Beginner to Advanced Guide

1. What Is TypeScript?

TypeScript is a programming language built on JavaScript that adds a static type system. It helps developers identify many mistakes during development and improves editor support and code maintainability.

TypeScript code is commonly compiled or transformed into JavaScript for execution.

Benefits

TypeScript does not automatically validate external data at runtime. API responses and user input still need runtime validation.

2. Setting Up TypeScript

Create a project:

mkdir typescript-guide
cd typescript-guide
npm init -y
npm install --save-dev typescript
npx tsc --init

Create src/index.ts:

const message: string = "Hello, TypeScript!";
console.log(message);

Compile the file:

npx tsc src/index.ts --outDir dist

Run the resulting JavaScript with Node.js:

node dist/index.js

For larger projects, configure tsconfig.json and a build script.

3. Basic Types

let username: string = "Aman";
let age: number = 21;
let isStudent: boolean = true;
let scores: number[] = [80, 90, 95];

TypeScript can often infer types automatically:

const language = "TypeScript";
const count = 10;

Avoid adding redundant annotations when inference is already clear. Add explicit types where they improve clarity, especially at function boundaries and public APIs.

4. Arrays and Tuples

Arrays

const names: string[] = ["Aman", "Riya"];
const marks: Array<number> = [90, 85, 92];

Tuples

Tuples represent arrays with known positions and types.

const userRecord: [number, string] = [1, "Aman"];

Use tuples when the positions have distinct meanings. Use objects when named fields are clearer.

5. Objects and Type Aliases

type User = {
  id: number;
  name: string;
  email?: string;
  readonly createdAt: Date;
};

const user: User = {
  id: 1,
  name: "Aman",
  createdAt: new Date()
};

TypeScript's readonly is a compile-time restriction, not a runtime security boundary.

6. Interfaces

Interfaces describe the shape of an object.

interface Product {
  id: number;
  name: string;
  price: number;
  description?: string;
}

const product: Product = {
  id: 101,
  name: "Keyboard",
  price: 1500
};

Interfaces and type aliases overlap significantly. Interfaces can be extended and declaration-merged; type aliases are especially useful for unions and more complex type expressions.

7. Functions and Return Types

function add(a: number, b: number): number {
  return a + b;
}

const multiply = (a: number, b: number): number => a * b;

Optional and Default Parameters

function greet(name: string, greeting = "Hello"): string {
  return `${greeting}, ${name}!`;
}

Void and Never

function logMessage(message: string): void {
  console.log(message);
}

function fail(message: string): never {
  throw new Error(message);
}

Use void for functions whose return value is not intended to be used. never describes values or functions that cannot complete normally with a value.

8. Union and Literal Types

A union permits one of several types.

let id: string | number;

id = 101;
id = "USR-101";

Literal types restrict values:

type Status = "pending" | "success" | "failed";

function showStatus(status: Status): void {
  console.log(status);
}

Unions are useful for statuses, modes, roles, and other controlled sets of values.

9. Type Narrowing

Narrowing lets TypeScript refine a type based on checks.

function printId(id: string | number): void {
  if (typeof id === "string") {
    console.log(id.toUpperCase());
  } else {
    console.log(id.toFixed(0));
  }
}

Useful narrowing tools include:

Discriminated Union

type Result =
  | { status: "success"; data: string }
  | { status: "error"; message: string };

function handleResult(result: Result): string {
  if (result.status === "success") {
    return result.data;
  }

  return result.message;
}

Discriminated unions help ensure that each state has the correct data.

10. The Unknown and Any Types

any disables many type checks.

let value: any = "hello";
value = 10;
value.notARealMethod();

Avoid using any without a good reason.

unknown is safer because a value must be checked before it is used.

function processValue(value: unknown): void {
  if (typeof value === "string") {
    console.log(value.toUpperCase());
  }
}

Prefer unknown for values whose type is not yet known.

11. Generics

Generics let reusable functions and types preserve information about input and output types.

function identity<T>(value: T): T {
  return value;
}

const text = identity<string>("Codify");
const number = identity<number>(100);

Generic Constraints

function getLength<T extends { length: number }>(value: T): number {
  return value.length;
}

Generic Interfaces

interface ApiResponse<T> {
  data: T;
  success: boolean;
}

const response: ApiResponse<string[]> = {
  data: ["JavaScript", "TypeScript"],
  success: true
};

Learn when to use generics and when a simple concrete type is more readable.

12. Enums and Alternatives

enum Direction {
  North,
  South,
  East,
  West
}

Enums are supported, but many applications prefer literal unions:

type DirectionName = "north" | "south" | "east" | "west";

Literal unions are often simpler for JSON data and API boundaries.

13. Utility Types

TypeScript provides built-in utility types.

Partial

Makes properties optional.

type UserUpdate = Partial<User>;

Required

Makes properties required.

type RequiredUser = Required<User>;

Pick and Omit

type PublicUser = Pick<User, "id" | "name">;
type UserWithoutEmail = Omit<User, "email">;

Readonly

type ReadonlyUser = Readonly<User>;

Record

type RolePermissions = Record<string, string[]>;

ReturnType and Parameters

type AddReturn = ReturnType<typeof add>;
type AddParameters = Parameters<typeof add>;

Use utility types to reduce duplication, but avoid complex type expressions that are difficult to maintain.

14. Classes and Access Modifiers

class BankAccount {
  private balance: number;

  constructor(initialBalance: number) {
    this.balance = initialBalance;
  }

  deposit(amount: number): void {
    if (amount <= 0) {
      throw new Error("Amount must be positive");
    }

    this.balance += amount;
  }

  getBalance(): number {
    return this.balance;
  }
}

Access modifiers include:

TypeScript's private is primarily a type-checking restriction. JavaScript's #privateField provides runtime-enforced private fields.

15. Modules and Imports

// utils.ts
export function formatPrice(price: number): string {
  return `₹${price.toFixed(2)}`;
}
// app.ts
import { formatPrice } from "./utils.js";

console.log(formatPrice(1499));

Import syntax and emitted paths depend on the module system and build configuration. Follow the chosen environment's conventions for Node.js or browser applications.

16. TypeScript with Promises and Async/Await

interface UserRecord {
  id: number;
  name: string;
}

async function getUser(id: number): Promise<UserRecord> {
  const response = await fetch(`/api/users/${id}`);

  if (!response.ok) {
    throw new Error("Failed to load user");
  }

  return response.json() as Promise<UserRecord>;
}

Important: the assertion above tells TypeScript to trust the returned shape; it does not verify the JSON at runtime. Validate untrusted API data before treating it as a UserRecord.

17. Type Assertions and the satisfies Operator

A type assertion tells TypeScript how you intend to treat a value.

const element = document.querySelector("#app") as HTMLElement;

Assertions do not perform runtime validation. Check that an element exists before using it.

The satisfies operator checks compatibility while preserving useful inference:

type Theme = {
  primary: string;
  secondary: string;
};

const theme = {
  primary: "#111111",
  secondary: "#eeeeee"
} satisfies Theme;

Use assertions sparingly; prefer narrowing and validation when possible.

18. TypeScript Configuration

A tsconfig.json file controls compiler behavior.

Important options include:

Enable strict checking for new projects when feasible. Configure module resolution and output according to your runtime and build tools.

19. TypeScript with React

TypeScript can describe component props and state.

type GreetingProps = {
  name: string;
  message?: string;
};

function Greeting({
  name,
  message = "Welcome"
}: GreetingProps) {
  return <h1>{message}, {name}!</h1>;
}

Learn:

Avoid using any as a shortcut for every React event or component prop.

20. TypeScript with Node.js

TypeScript can be used in backend applications.

Learn:

Do not assume that a TypeScript type validates incoming HTTP requests. Validate requests at runtime.

21. Testing TypeScript Applications

Testing tools can check application behavior independently of type checking.

Common categories:

Use a test runner such as Vitest or Jest, depending on the project.

Test both valid and invalid inputs. Keep type checking in the build or CI pipeline, because running tests alone may not catch every type error.

22. Common TypeScript Mistakes

  1. Using any everywhere.
  2. Trusting API data without runtime validation.
  3. Treating type assertions as validation.
  4. Overusing non-null assertions (!).
  5. Writing unnecessarily complicated generics.
  6. Ignoring strict compiler errors.
  7. Duplicating types across files.
  8. Confusing optional fields with fields that accept null.
  9. Using private as if it were a security boundary.
  10. Assuming types exist at runtime after compilation.
  11. Ignoring module-system configuration.
  12. Forgetting to test error cases.

23. Practical Projects

Beginner

Intermediate

Advanced

24. Four-Week Learning Roadmap

Week 1

Learn basic types, arrays, objects, functions, and inference.

Week 2

Practice unions, narrowing, interfaces, type aliases, and generics.

Week 3

Learn utility types, modules, configuration, classes, and async code.

Week 4

Build a frontend or backend project and add testing, validation, and CI type checks.

25. Final Checklist

Conclusion

TypeScript helps developers maintain reliable JavaScript applications by making data structures and expectations explicit. Learn the fundamentals, enable strict checking, validate external data, and apply the language to real projects.

More guides