TypeScript has become one of the most popular programming languages for modern web development. Developed and maintained by Microsoft, TypeScript extends JavaScript by adding static typing, interfaces, decorators, generics, and many other enterprise-level features.
Whether you are building small applications or large-scale enterprise software, TypeScript helps you write cleaner, safer, and more maintainable code.
In this guide, you will learn TypeScript from beginner to advanced concepts with practical examples.
What is TypeScript?
TypeScript is an open-source programming language that builds on JavaScript by adding optional static types.
TypeScript code is converted (transpiled) into standard JavaScript before execution.
JavaScript Example
function greet(name) {
return "Hello " + name;
}
console.log(greet(123));
Output:
Hello 123
No error occurs.
TypeScript Example
function greet(name: string): string {
return "Hello " + name;
}
greet(123);
Output:
Argument of type 'number' is not assignable to parameter of type 'string'
TypeScript catches the error before deployment.
Why Use TypeScript?
Advantages
- Static Type Checking
- Better IDE Support
- Improved Code Readability
- Easier Refactoring
- Better Team Collaboration
- Enhanced Maintainability
- Enterprise-Scale Development Support
Installing TypeScript
Using NPM
npm install -g typescript
Verify installation:
tsc --version
Initialize configuration:
tsc --init
This creates a tsconfig.json file.
Basic Data Types
String
let username: string = "John";
Number
let age: number = 25;
Boolean
let isActive: boolean = true;
Array
let skills: string[] = ["JavaScript", "TypeScript"];
Tuple
let employee: [number, string] = [1, "David"];
Enum
enum Status {
Pending,
Approved,
Rejected
}
let currentStatus: Status = Status.Approved;
Any
let value: any = "Hello";
value = 100;
Functions
Function Parameters
function add(a: number, b: number): number {
return a + b;
}
Optional Parameters
function display(name: string, city?: string) {
console.log(name, city);
}
Default Parameters
function greet(name: string = "Guest") {
console.log(name);
}
Objects
let person: {
name: string;
age: number;
} = {
name: "John",
age: 30
};
Interfaces
Interfaces define the structure of an object.
interface User {
id: number;
name: string;
email: string;
}
Usage:
const user: User = {
id: 1,
name: "John",
email: "john@example.com"
};
Type Aliases
type Product = {
id: number;
name: string;
price: number;
};
Union Types
let id: string | number;
id = 100;
id = "ABC123";
Literal Types
let role: "admin" | "user" | "editor";
role = "admin";
Type Assertions
let value: any = "Hello";
let length = (value as string).length;
Classes
class Employee {
name: string;
constructor(name: string) {
this.name = name;
}
work() {
console.log(`${this.name} is working`);
}
}
Access Modifiers
Public
public name: string;
Private
private salary: number;
Protected
protected department: string;
Inheritance
class Person {
speak() {
console.log("Speaking");
}
}
class Developer extends Person {
code() {
console.log("Coding");
}
}
Abstract Classes
abstract class Animal {
abstract makeSound(): void;
}
Generics
Generics enable reusable components.
function identity<T>(value: T): T {
return value;
}
identity<string>("Hello");
identity<number>(100);
Generic Interfaces
interface ApiResponse<T> {
data: T;
success: boolean;
}
Generic Classes
class Repository<T> {
private items: T[] = [];
add(item: T) {
this.items.push(item);
}
}
Utility Types
Partial
interface User {
name: string;
email: string;
}
type UpdateUser = Partial<User>;
Required
type RequiredUser = Required<User>;
Readonly
type ReadonlyUser = Readonly<User>;
Pick
type UserInfo = Pick<User, "name" | "email">;
Omit
type UserWithoutEmail = Omit<User, "email">;
Advanced Types
Intersection Types
type Person = {
name: string;
};
type Employee = {
employeeId: number;
};
type Staff = Person & Employee;
keyof Operator
interface User {
name: string;
age: number;
}
type UserKeys = keyof User;
Output:
"name" | "age"
Mapped Types
type ReadOnly<T> = {
readonly [K in keyof T]: T[K];
};
Conditional Types
type IsString<T> = T extends string ? true : false;
Type Guards
function print(value: string | number) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
Modules
Export
export function add(a: number, b: number) {
return a + b;
}
Import
import { add } from "./math";
Decorators
Enable decorators in tsconfig.json.
function Logger(target: Function) {
console.log(target);
}
@Logger
class User {}
Commonly used in Angular and enterprise applications.
Async and Await
async function getUsers() {
const response = await fetch("/api/users");
return await response.json();
}
Working with APIs
interface User {
id: number;
name: string;
}
async function fetchUsers(): Promise<User[]> {
const response = await fetch("/api/users");
return response.json();
}
TypeScript Best Practices
Avoid Using Any
Bad:
let data: any;
Good:
let data: string;
Use Interfaces for Contracts
interface Customer {
id: number;
name: string;
}
Enable Strict Mode
{
"strict": true
}
Prefer Readonly
readonly id: number;
Use Generics
Avoid duplication and increase reusability.
Common Interview Questions
What is TypeScript?
A statically typed superset of JavaScript that compiles to JavaScript.
Difference Between Interface and Type?
Interfaces are extendable and mainly used for object contracts, while types are more flexible and support unions and intersections.
What are Generics?
Generics allow reusable code that works with multiple data types while maintaining type safety.
What is Type Erasure?
TypeScript removes type information during compilation and generates pure JavaScript.
What are Decorators?
Special annotations that add metadata or behavior to classes, methods, properties, or parameters.
Conclusion
TypeScript is no longer just an optional enhancement for JavaScript developers. It has become a standard choice for enterprise applications, Angular projects, React applications, Node.js backends, and modern full-stack development.
By mastering TypeScript fundamentals such as types, interfaces, classes, and generics, and progressing toward advanced concepts like mapped types, conditional types, decorators, and utility types, developers can build scalable, maintainable, and robust applications with confidence.
Investing time in learning TypeScript today will significantly improve your development productivity and code quality in the long run.