TypeScript Basics
๐น What is TypeScript?
Section titled โ๐น 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?
Section titled โโจ 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
Section titled โ๐น Installing TypeScriptโTo install TypeScript globally, use npm (Node Package Manager):
npm install -g typescript
To check the installation:
tsc --version
You can compile a TypeScript file (.ts
) into JavaScript (.js
) using:
tsc filename.ts
๐น Variables and Type Annotations
Section titled โ๐น Variables and Type AnnotationsโUnlike JavaScript, TypeScript allows defining types explicitly:
let name: string = "Alice"; // String typelet age: number = 30; // Number typelet isActive: boolean = true; // Boolean type
Type Inference
Section titled โType InferenceโTypeScript can infer types automatically:
let city = "New York"; // Automatically inferred as a string
๐น Basic Data Types in TypeScript
Section titled โ๐น Basic Data Types in TypeScriptโTypeScript includes all JavaScript types, plus additional types:
Type | Example |
---|---|
String | "Hello, TypeScript" |
Number | 42 , 3.14 |
Boolean | true , false |
Array | [1, 2, 3] or Array<number> |
Tuple | [string, number] โ ["Alice", 25] |
Enum | enum Color { Red, Green, Blue } |
Any | let data: any = "Hello"; |
Void | function logMessage(): void {} |
Never | function throwError(): never { throw new Error("Error"); } |
Example usage of different types:
Section titled โExample usage of different types:โlet names: string[] = ["Alice", "Bob", "Charlie"];let user: [string, number] = ["Alice", 25]; // Tupleenum Color { Red, Green, Blue };let favoriteColor: Color = Color.Green;
๐น Functions in TypeScript
Section titled โ๐น 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)
Section titled โArrow Functions (ES6 Style)โconst multiply = (a: number, b: number): number => a * b;
Optional & Default Parameters
Section titled โOptional & Default Parametersโfunction greet(name: string, age?: number) { return `Hello, ${name}!`;}console.log(greet("Alice")); // Output: Hello, Alice!
๐น Interfaces in TypeScript
Section titled โ๐น 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:
Section titled โInterfaces can also be used with functions:โinterface MathOperation { (a: number, b: number): number;}
const sum: MathOperation = (x, y) => x + y;
๐น Classes in TypeScript
Section titled โ๐น 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
Section titled โ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
Section titled โ๐น Generics in TypeScriptโGenerics allow creating flexible and reusable components:
function identity<T>(value: T): T { return value;}
console.log(identity<number>(42)); // Output: 42console.log(identity<string>("Hello")); // Output: Hello
๐น TypeScript vs JavaScript
Section titled โ๐น TypeScript vs JavaScriptโFeature | TypeScript | JavaScript |
---|---|---|
Typing | Static (Strong) | Dynamic (Weak) |
Error Detection | Compile-time | Runtime |
Interfaces | Yes | No |
OOP Support | Advanced | Limited |
Compilation | Requires tsc | Runs directly in browsers |
๐น Setting Up a TypeScript Project
Section titled โ๐น Setting Up a TypeScript Projectโ1๏ธโฃ Initialize a project
npm init -ynpm install typescript --save-devnpx tsc --init
2๏ธโฃ Create a TypeScript file (index.ts)
const message: string = "Hello, TypeScript!";console.log(message);
3๏ธโฃ Compile TypeScript to JavaScript
tsc index.ts
4๏ธโฃ Run JavaScript output
node index.js
๐น Conclusion
Section titled โ๐น 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!