TypeScript Tutorial
JavaScript with static types. Catch bugs early and write self-documenting code.
- Topics
- 29
- Full lessons
- 29
- Est. hours
- ~5
- Interview Qs
- 26
Overview
TypeScript is a superset of JavaScript that adds a static type system. The TypeScript compiler checks your code and then emits plain JavaScript, so it runs anywhere JavaScript runs.
Types catch whole categories of bugs before your code ever runs and make editors far more helpful with autocompletion and refactoring.
What you will learn
- Annotate values, functions and objects with types
- Model data with interfaces, unions and generics
- Narrow types safely with type guards
- Configure tsconfig.json for real projects
Prerequisites
You will get the most from this track if you already know:
Learning path
The recommended sequence, from beginner to advanced. Each stage builds on the one before.
- 1Getting Started · 5 topics · BeginnerIntroduction to TypeScript · JavaScript vs TypeScript · Installation and Configuration · Basic Types · Type Inference
- 2Modelling Data · 6 topics · Beginner → IntermediateArrays and Tuples · Objects and Type Aliases · Interfaces · Union and Intersection Types · Literal Types · Enums
- 3Functions · 3 topics · IntermediateFunctions and Function Types · Optional and Default Parameters · Generics
- 4Classes · 4 topics · IntermediateClasses · Access Modifiers · Inheritance · Abstract Classes
- 5Advanced Types · 4 topics · Intermediate → AdvancedType Narrowing · Type Guards · Utility Types · keyof and typeof
- 6Projects · 7 topics · AdvancedModules · tsconfig.json · Strict Mode · Async Programming · TypeScript with React · TypeScript with Angular · Practical Projects
Complete topic list
29 topicsGetting Started
5 topics- Introduction to TypeScriptBeginner5m
- JavaScript vs TypeScriptBeginner5m
- Installation and ConfigurationBeginner5m
- Basic TypesBeginner5m
- Type InferenceBeginner5m
Modelling Data
6 topics- Arrays and TuplesBeginner5m
- Objects and Type AliasesBeginner5m
- InterfacesIntermediate5m
- Union and Intersection TypesIntermediate5m
- Literal TypesIntermediate5m
- EnumsIntermediate6m
Functions
3 topics- Functions and Function TypesIntermediate5m
- Optional and Default ParametersIntermediate5m
- GenericsIntermediate5m
Classes
4 topics- ClassesIntermediate5m
- Access ModifiersIntermediate5m
- InheritanceIntermediate5m
- Abstract ClassesIntermediate5m
Advanced Types
4 topics- Type NarrowingIntermediate6m
- Type GuardsIntermediate5m
- Utility TypesAdvanced5m
- keyof and typeofAdvanced5m
Projects
7 topics- ModulesAdvanced5m
- tsconfig.jsonAdvanced5m
- Strict ModeAdvanced5m
- Async ProgrammingAdvanced6m
- TypeScript with ReactAdvanced6m
- TypeScript with AngularAdvanced6m
- Practical ProjectsAdvanced6m
Code example
A taste of the track, from Introduction to TypeScript.
interface User {
name: string;
email: string;
}
function sendWelcome(user: User): string {
return `Welcome, ${user.name}! We sent a mail to ${user.emial}`;
// ~~~~~
// ✗ Error: Property 'emial' does not exist on type 'User'. Did you mean 'email'?
}
sendWelcome({ name: 'Asha' });
// ~~~~~~~~~~~~~~~~
// ✗ Error: Property 'email' is missing in type '{ name: string; }'
The code does not compile. TypeScript reports both bugs — the misspelled property and the missing email — before the code ever runs. Plain JavaScript would have printed “…mail to undefined”.
Practice exercises
Add types to this function so that calling it with a string causes an error: function area(width, height) { return width * height; }
List two situations where you would choose plain JavaScript and two where you would choose TypeScript.
Add two npm scripts to package.json: "build" that compiles the project and "typecheck" that only checks types.
Declare: a product name (text), a price (number), an inStock flag, and a discountCode that may be null. Then write a function printProduct that returns nothing.
What types are inferred? (a) let x = 3.5 (b) const y = true (c) const z = [true, false] (d) let w = null
Type a function minMax(nums: number[]) that returns a tuple [min, max] with named elements.
Show all 29 exercises
Create a type Address (street, city, pin, optional landmark) and a type Customer with a readonly id, name and an array of addresses.
Create an interface Shape with area(): number. Create Circle and Rectangle classes that implement it, and a function totalArea(shapes: Shape[]).
Model a payment method that is either a card (cardNumber, expiry) or UPI (upiId), with a "method" discriminator, and write describe(p) returning a string for each.
Create a Theme type from the array const themes = ["light", "dark", "system"] and a function setTheme(t: Theme).
Create a string enum LogLevel (Debug, Info, Warn, Error) and a function log(level, msg) that prefixes the message with the level value.
Write a type Validator = (value: string) => string | null (null means valid) and a function validateAll(value, validators: Validator[]) that returns the first error or null.
Write formatDate(date: Date, options?) where options has optional locale (default "en-IN") and withTime (default false).
Write a generic function last<T>(items: T[]): T | undefined that returns the final element.
Write a class BankAccount with a readonly accountNumber, a private balance starting at 0, deposit(amount) and a balance getter. Reject negative deposits.
In class Car, make engineNumber private readonly, speed protected and model public. Add a static wheels = 4.
Create class AppError extends Error with a statusCode, and NotFoundError extends AppError that always uses 404 and a message like "User not found".
Create abstract class Employee with name, an abstract monthlyPay(): number and a normal method payslip() returning "<name>: ₹<pay>". Implement FullTime (salary/12) and Contractor (hours × rate).
Write describe(x: string | string[] | undefined) that returns "nothing", the string itself, or the items joined with commas.
Write isNonEmptyString(x: unknown): x is string that returns true only for strings with at least one non-space character, and use it to filter ["a", "", 3, " b "].
Given interface Product { id: number; name: string; price: number; stock: number }, create: ProductForm (no id), ProductPatch (all form fields optional) and StockMap (Record of product name to stock).
Write a generic getProp<T, K extends keyof T>(obj: T, key: K): T[K] and show that getProp(user, "age") returns number for user = { name: "Asha", age: 24 }.
You install the JS library "slugify-lite" and get “Could not find a declaration file”. Write a declaration for its default export slugify(text: string): string.
Write a tsconfig.json for a Node.js API that compiles src/ to dist/ with strict checks and source maps.
Fix all strict errors: function firstUpper(list) { return list[0].toUpperCase(); }
Write getJson<T>(url: string, fallback: T): Promise<T> that returns the parsed JSON, or the fallback if the request fails for any reason.
Create a typed Avatar component with props src (string), alt (string), size ("sm" | "md" | "lg", default "md") and optional onClick.
Write a typed UserService with a method getById(id: number): Observable<User> using HttpClient, where User has id, name and email.
Project 2 starter: write sortBy<T>(items: T[], key: keyof T, dir: "asc" | "desc" = "asc"): T[] that returns a sorted copy.
Common interview questions
- What is the difference between interface and type?
- What is TypeScript and why use it?
- any vs unknown vs never?
- Does TypeScript run in the browser?
- What is type inference?
- Arrays vs tuples?
- How do optional and default parameters differ?
- What are literal types?
- Why use generics instead of any?
- What are union and intersection types?
- What is type narrowing?
- Name some built-in utility types.
- What does "strict": true enable?
- What is a type guard?
- What is a discriminated union?
- How do you constrain a generic?
- What do public, private, protected and readonly do in TypeScript classes?
- What is the difference between abstract classes and interfaces in TypeScript?
- How do you type async functions?
- Which tsconfig options matter most?
- Explain keyof and typeof in type positions.
- Enums vs union of string literals?
- What are mapped and conditional types?
- How do you type React props and events?
- How does TypeScript help in Angular?
- When is a type assertion (as) dangerous?