TypeScript Fundamentals for Angular - Textnotes

TypeScript Fundamentals for Angular


This chapter explains the essential TypeScript concepts needed for Angular development, including data types, interfaces, classes, access modifiers, generics, arrow functions, and module import/export mechanisms.

1. Types, Interfaces, and Classes

Types

Types define the type of data a variable can hold.


let id: number = 101;
let name: string = "Angular";
let isActive: boolean = true;
let tags: string[] = ["web", "framework"];

Interfaces

Interfaces define the structure of an object.


interface User {
id: number;
name: string;
email: string;
}

const user: User = {
id: 1,
name: "John",
email: "john@example.com"
};

Classes

Classes are used to create objects with properties and methods.


class Person {
name: string;
age: number;

constructor(name: string, age: number) {
this.name = name;
this.age = age;
}

getDetails() {
return `${this.name} is ${this.age} years old`;
}
}

2. Access Modifiers (public, private, protected)

Access modifiers control visibility of class properties and methods.

public

Accessible from anywhere.


class Test {
public value = 10;
}

private

Accessible only inside the same class.


class Demo {
private secret = "hidden";
}

protected

Accessible in the class and its derived subclasses.


class Base {
protected data = 5;
}

class Child extends Base {
show() {
return this.data;
}
}

3. Generics

Generics allow reusable components that work with different data types.


function identity<T>(value: T): T {
return value;
}

let num = identity<number>(10);
let str = identity<string>("hello");

Generics can also be used with classes and interfaces.


class Box<T> {
content: T;

constructor(content: T) {
this.content = content;
}
}

4. Arrow Functions

Arrow functions provide a shorter syntax compared to regular JavaScript functions.

Traditional function


function add(a: number, b: number) {
return a + b;
}

Arrow function


const add = (a: number, b: number) => a + b;

Example with array


const numbers = [1, 2, 3];

const doubled = numbers.map(n => n * 2);

Arrow functions automatically bind this, which is helpful in Angular components.

5. Modules and Imports/Exports

TypeScript organizes code using modules.

Each file is treated as a separate module.

Exporting a class


export class Logger {
log(msg: string) {
console.log(msg);
}
}

Importing a class


import { Logger } from './logger';

const log = new Logger();
log.log("Hello Angular");

Exporting multiple items


export const pi = 3.14;
export function greet() { return "Hello"; }

Default export


export default class Utility { }

Imported as:


import Utility from './utility';