Introduction to TypeScript
Learn TypeScript - JavaScript with static type checking. Add type safety to your JavaScript code and catch errors at compile time.

What is TypeScript?#
TypeScript is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale. It's a superset of JavaScript that adds static type definitions. TypeScript compiles to plain JavaScript, which means any valid JavaScript code is also valid TypeScript code.
TypeScript was developed by Microsoft and first released in 2012. It adds optional static typing, classes, interfaces, and other features to JavaScript, making it easier to build large-scale applications. TypeScript helps catch errors during development rather than at runtime, leading to more robust and maintainable code.
Why Use TypeScript?#
- Type Safety - Catch errors at compile time
- Better IDE Support - Autocomplete, refactoring, navigation
- Self-Documenting Code - Types serve as documentation
- Easier Refactoring - Change code with confidence
- Better for Large Projects - Manage complexity better
Installation#
Install TypeScript globally or locally in your project:
# Global installation
npm install -g typescript
# Local installation (recommended)
npm install --save-dev typescript
# Verify installation
tsc --versionInitialize TypeScript in your project:
# Create tsconfig.json
tsc --init
# Or create manually
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}Basic Types#
TypeScript provides several basic types:
// Primitive types
let name: string = "John";
let age: number = 30;
let isActive: boolean = true;
let data: null = null;
let value: undefined = undefined;
// Arrays
let items: string[] = ["apple", "banana"];
let numbers: Array<number> = [1, 2, 3];
// Tuples
let tuple: [string, number] = ["hello", 10];
// Objects
let user: { name: string; age: number } = { name: "John", age: 30 };
// Any (avoid when possible)
let anything: any = "can be anything";
// Unknown (safer than any)
let unknownValue: unknown = "could be anything";
// Void
function log(message: string): void {
console.log(message);
}
// Never (for functions that never return)
function throwError(): never {
throw new Error("Error");
}Functions#
Type functions with parameter and return types:
// Function declaration
function greet(name: string): string {
return `Hello, ${name}`;
}
// Arrow function
const add = (a: number, b: number): number => {
return a + b;
};
// Optional parameters
function greetOptional(name: string, title?: string): string {
return title ? `Hello, ${title} ${name}` : `Hello, ${name}`;
}
// Default parameters
function greetDefault(name: string, greeting: string = "Hello"): string {
return `${greeting}, ${name}`;
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((acc, n) => acc + n, 0);
}
// Function overloads
function process(value: string): string;
function process(value: number): number;
function process(value: string | number): string | number {
return typeof value === 'string' ? value.toUpperCase() : value * 2;
}Interfaces#
Define object shapes with interfaces:
interface User {
name: string;
age: number;
email?: string; // Optional property
readonly id: number; // Read-only property
}
const user: User = {
name: "John",
age: 30,
id: 1
};
// user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property
// Extending interfaces
interface Admin extends User {
permissions: string[];
}
const admin: Admin = {
name: "Jane",
age: 25,
id: 2,
permissions: ["read", "write", "delete"]
};
// Interface for functions
interface SearchFunction {
(source: string, subString: string): boolean;
}
const mySearch: SearchFunction = function(src, sub) {
return src.indexOf(sub) > -1;
};Classes#
TypeScript enhances JavaScript classes with type annotations:
class Person {
private name: string;
protected age: number;
public email: string;
constructor(name: string, age: number, email: string) {
this.name = name;
this.age = age;
this.email = email;
}
greet(): string {
return `Hello, I'm ${this.name}`;
}
get getName(): string {
return this.name;
}
set setName(value: string) {
this.name = value;
}
}
class Employee extends Person {
private salary: number;
constructor(name: string, age: number, email: string, salary: number) {
super(name, age, email);
this.salary = salary;
}
getSalary(): number {
return this.salary;
}
}
const employee = new Employee("John", 30, "john@example.com", 50000);
console.log(employee.greet()); // "Hello, I'm John"Generics#
Create reusable components with generics:
// Generic function
function identity<T>(arg: T): T {
return arg;
}
const output = identity<string>("hello");
const number = identity<number>(42);
// Generic interface
interface Box<T> {
value: T;
}
const stringBox: Box<string> = { value: "hello" };
const numberBox: Box<number> = { value: 42 };
// Generic class
class Container<T> {
private items: T[] = [];
add(item: T): void {
this.items.push(item);
}
get(index: number): T {
return this.items[index];
}
}
const stringContainer = new Container<string>();
stringContainer.add("hello");
stringContainer.add("world");Union and Intersection Types#
// Union type
type StringOrNumber = string | number;
function processValue(value: StringOrNumber): string {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value.toString();
}
// Intersection type
type Person = {
name: string;
age: number;
};
type Employee = {
employeeId: number;
department: string;
};
type EmployeePerson = Person & Employee;
const emp: EmployeePerson = {
name: "John",
age: 30,
employeeId: 123,
department: "Engineering"
};Type Guards#
function isString(value: unknown): value is string {
return typeof value === 'string';
}
function process(value: string | number) {
if (isString(value)) {
// TypeScript knows value is string here
console.log(value.toUpperCase());
} else {
// TypeScript knows value is number here
console.log(value.toFixed(2));
}
}Compiling TypeScript#
# Compile single file
tsc app.ts
# Compile with watch mode
tsc --watch
# Compile entire project
tsc
# With tsconfig.json
tsc --project tsconfig.jsonBest Practices#
- Enable strict mode in tsconfig.json
- Use interfaces for object shapes
- Avoid 'any' type when possible
- Use type guards for runtime type checking
- Leverage TypeScript's type inference
- Use generics for reusable code
- Document complex types with comments
TypeScript brings the benefits of static typing to JavaScript, making your code more robust, maintainable, and easier to work with. It's especially valuable in large codebases and team environments where type safety helps prevent bugs and improves developer productivity.