TypeScript Notes
What is TypeScript?
A superset of JavaScript.
Adds static typing to JavaScript.
Code is compiled (transpiled) to plain JavaScript.
Key Features
Static Type Checking: Detect errors at compile time.
Type Inference: Automatically determines types when possible.
Interfaces and Type Aliases: Define shapes of objects.
Classes and Access Modifiers (public, private, protected).
Enums: Define a set of named constants.
Generics: Create reusable and type-safe components/functions.
Basic Types
typescript
Copy
Edit
let isActive: boolean = true;
let age: number = 30;
let userName: string = "Alex";
let numbers: number[] = [1, 2, 3];
let anything: any = "Could be anything";
Functions
typescript
Copy
Edit
function add(x: number, y: number): number {
return x + y;
}
Parameters and return types are typed.
Interfaces
typescript
Copy
Edit
interface User {
name: string;
age: number;
}
const user: User = { name: "Sam", age: 25 };
Classes
typescript
Copy
Edit
class Animal {
constructor(public name: string) {}
move(distance: number): void {
console.log(`${this.name} moved ${distance} meters.`);
}
}
Generics
typescript
Copy
Edit
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello");
T can be any type passed during function call.
Type Aliases
typescript
Copy
Edit
type ID = number | string;
let userId: ID = 101;
Advantages of TypeScript
Catches errors early.
Makes large codebases easier to maintain.
Great tooling support (autocompletion, navigation).
Disadvantages
Extra compilation step.
Initial learning curve for JavaScript developers.