Skip to content

TypeScript Basics

πŸ”Ή What is TypeScript?

TypeScript is a strongly typed, object-oriented, and compiled superset of JavaScript developed by Microsoft. It enhances JavaScript by adding static typing, interfaces, and better tooling support, making it ideal for large-scale applications.

✨ Why Use TypeScript?

βœ… Type Safety – Catches errors at compile time, reducing runtime issues.
βœ… Improved Readability & Maintainability – Makes large codebases easier to manage.
βœ… Supports Modern JavaScript Features – Fully supports ES6+ features.
βœ… Better IDE Support – Provides better IntelliSense and autocompletion.


πŸ”Ή Installing TypeScript

To install TypeScript globally, use npm (Node Package Manager):

Terminal window
npm install -g typescript

To check the installation:

Terminal window
tsc --version

You can compile a TypeScript file (.ts) into JavaScript (.js) using:

Terminal window
tsc filename.ts

πŸ”Ή Variables and Type Annotations

Unlike JavaScript, TypeScript allows defining types explicitly:

let name: string = "Alice"; // String type
let age: number = 30; // Number type
let isActive: boolean = true; // Boolean type

Type Inference

TypeScript can infer types automatically:

let city = "New York"; // Automatically inferred as a string

πŸ”Ή Basic Data Types in TypeScript

TypeScript includes all JavaScript types, plus additional types:

TypeExample
String"Hello, TypeScript"
Number42, 3.14
Booleantrue, false
Array[1, 2, 3] or Array<number>
Tuple[string, number] β†’ ["Alice", 25]
Enumenum Color { Red, Green, Blue }
Anylet data: any = "Hello";
Voidfunction logMessage(): void {}
Neverfunction throwError(): never { throw new Error("Error"); }

Example usage of different types:

let names: string[] = ["Alice", "Bob", "Charlie"];
let user: [string, number] = ["Alice", 25]; // Tuple
enum Color { Red, Green, Blue };
let favoriteColor: Color = Color.Green;

πŸ”Ή Functions in TypeScript

Functions in TypeScript allow type annotations for parameters and return values:

function add(a: number, b: number): number {
return a + b;
}
console.log(add(5, 3)); // Output: 8

Arrow Functions (ES6 Style)

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

Optional & Default Parameters

function greet(name: string, age?: number) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Output: Hello, Alice!

πŸ”Ή Interfaces in TypeScript

Interfaces define the structure of an object:

interface User {
name: string;
age: number;
isAdmin?: boolean; // Optional property
}
let user: User = { name: "Alice", age: 30 };

Interfaces can also be used with functions:

interface MathOperation {
(a: number, b: number): number;
}
const sum: MathOperation = (x, y) => x + y;

πŸ”Ή Classes in TypeScript

TypeScript supports OOP principles like classes, inheritance, and access modifiers:

class Person {
private name: string; // Private property
protected age: number; // Accessible in derived classes
public city: string; // Public property
constructor(name: string, age: number, city: string) {
this.name = name;
this.age = age;
this.city = city;
}
getDetails(): string {
return `${this.name} is ${this.age} years old from ${this.city}.`;
}
}
let person = new Person("Alice", 30, "New York");
console.log(person.getDetails());

Class Inheritance

typescript class Employee extends Person { constructor(name: string, age: number, city: string, public position: string) { super(name, age, city); } }

let employee = new Employee(β€œBob”, 28, β€œSan Francisco”, β€œDeveloper”); console.log(employee.getDetails()); πŸ”Ή TypeScript and the DOM Manipulating the DOM with TypeScript is similar to JavaScript but with strict type checking:

const button = document.getElementById("btn") as HTMLButtonElement;
button.addEventListener("click", () => {
alert("Button Clicked!");
});

πŸ”Ή Generics in TypeScript

Generics allow creating flexible and reusable components:

function identity<T>(value: T): T {
return value;
}
console.log(identity<number>(42)); // Output: 42
console.log(identity<string>("Hello")); // Output: Hello

πŸ”Ή TypeScript vs JavaScript

FeatureTypeScriptJavaScript
TypingStatic (Strong)Dynamic (Weak)
Error DetectionCompile-timeRuntime
InterfacesYesNo
OOP SupportAdvancedLimited
CompilationRequires tscRuns directly in browsers

πŸ”Ή Setting Up a TypeScript Project

1️⃣ Initialize a project

Terminal window
npm init -y
npm install typescript --save-dev
npx tsc --init

2️⃣ Create a TypeScript file (index.ts)

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

3️⃣ Compile TypeScript to JavaScript

Terminal window
tsc index.ts

4️⃣ Run JavaScript output

Terminal window
node index.js

πŸ”Ή Conclusion

TypeScript enhances JavaScript by adding static typing, interfaces, classes, and advanced OOP features. It is widely used for frontend frameworks (Angular, React) and backend development (Node.js, NestJS).

πŸš€ Next Steps? Explore TypeScript with React, Node.js, or Angular!