Chapter 2: TypeScript Fundamentals
Introduction to TypeScript:
TypeScript is a statically-typed superset of JavaScript that compiles to plain JavaScript. It brings static typing and additional features to JavaScript, improving code maintainability and catching potential errors during development. TypeScript is widely used in Angular development due to its strong integration with the framework.
Working with TypeScript features:
- Variables and Data Types:
- Declaring variables using
let
andconst
keywords:
let age: number = 25;
const name: string = "John Doe";
- Working with basic data types such as number, string, boolean, etc.:
let age: number = 25;
let name: string = "John Doe";
let isStudent: boolean = true;
- Utilizing type annotations to explicitly define variable types:
let age: number;
let name: string;
age = 25;
name = "John Doe";
- Leveraging type inference to automatically determine variable types:
let age = 25; // TypeScript infers the type as number
let name = "John Doe"; // TypeScript infers the type as string
- Functions:
- Defining functions with parameter types and return types:
function addNumbers(a: number, b: number): number {
return a + b;
}
- Understanding optional and default parameters:
function greet(name: string, message?: string): void {
if (message) {
console.log(`Hello, ${name}! ${message}`);
} else {
console.log(`Hello, ${name}!`);
}
}
- Utilizing function overloading to define multiple function signatures:
function getResult(value: number): number;
function getResult(value: string): string;
function getResult(value: any): any {
if (typeof value === "number") {
return value * 2;
} else if (typeof value === "string") {
return value.toUpperCase();
}
}
- Working with arrow functions and lexical scoping:
const multiply = (a: number, b: number): number => a * b;
const greeting = (name: string): void => {
console.log(`Hello, ${name}!`);
};
- Classes and Objects:
- Creating classes to model real-world entities:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
sayHello(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person = new Person("John Doe", 25);
person.sayHello();
- Defining properties, methods, and constructors within classes:
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
const rectangle = new Rectangle(10, 5);
const area = rectangle.getArea();
console.log(`Area: ${area}`);
- Understanding access modifiers (public, private, protected) for encapsulation:
class Car {
private brand: string;
protected year: number;
constructor(brand: string, year: number) {
this.brand = brand;
this.year = year;
}
protected startEngine(): void {
console.log("Engine started.");
}
}
class Sedan extends Car {
drive(): void {
console.log(`Driving a ${this.brand} sedan`);
}
}
const sedan = new Sedan("Honda", 2021);
sedan.drive();
- Implementing inheritance and polymorphism using class inheritance:
class Animal {
makeSound(): void {
console.log("Animal makes sound.");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Dog barks.");
}
}
const animal: Animal = new Dog();
animal.makeSound();
- Working with abstract classes and interfaces for defining contracts:
abstract class Shape {
abstract getArea(): number;
abstract getPerimeter(): number;
}
class Circle extends Shape {
radius: number;
constructor(radius: number) {
super();
this.radius = radius;
}
getArea(): number {
return Math.PI * this.radius * this.radius;
}
getPerimeter(): number {
return 2 * Math.PI * this.radius;
}
}
const circle: Shape = new Circle(5);
const area = circle.getArea();
const perimeter = circle.getPerimeter();
TypeScript decorators and their usage in Angular:
TypeScript decorators provide a way to modify the behavior of classes, methods, properties, and parameters at design time. In Angular, decorators play a crucial role in configuring and customizing various aspects of components, services, and modules.
- @Component decorator:
- Using the @Component decorator to define Angular components:
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
// Component logic goes here
}
- Configuring component metadata such as selector, template, styles, etc.
- Binding component properties and methods to the template
- Handling component events using event bindings
- @Injectable decorator:
- Using the @Injectable decorator to define Angular services:
import { Injectable } from "@angular/core";
@Injectable({
providedIn: "root"
})
export class DataService {
// Service logic goes here
}
- Registering services with the Angular dependency injection system
- Understanding the different provider options for service registration
- @NgModule decorator:
- Using the @NgModule decorator to define Angular modules:
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent } from "./app.component";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
// Module logic goes here
}
- Declaring and importing components, directives, and pipes within modules
- Configuring module providers for dependency injection
- Understanding the role of entry components and bootstrap components
Throughout this chapter, you’ll learn the fundamentals of TypeScript
and how to leverage its features to build robust and maintainable Angular applications. You’ll explore various TypeScript concepts, such as variables, data types, functions, classes, and decorators. Each concept will be accompanied by real-life code implementation examples to demonstrate their practical usage within an Angular project.