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}!`);
};