Login Register
×

TypeScript Syntax

1๏ธโƒฃ TypeScript Syntax vs. JavaScript Syntax

TypeScript extends JavaScript, meaning you can write regular JavaScript code and add extra TypeScript features.

โœ” JavaScript Code (Valid in TypeScript)

let message = "Hello, World!";
console.log(message);

โœ” TypeScript Code with Type Annotations

let message: string = "Hello, World!";
console.log(message);

๐Ÿ‘‰ Key difference: The : string specifies that message must always be a string.

2๏ธโƒฃ Variables and Data Types in TypeScript

In TypeScript, you must define data types for variables.

๐Ÿ”น Declaring Variables with Type Annotations

let name: string = "John";  // String type
let age: number = 25; // Number type
let isStudent: boolean = true; // Boolean type

โœ… TypeScript enforces the correct data type, preventing unexpected errors.

๐Ÿ”น Using let, const and var

KeywordScopeReassignment Allowed?
letBlockโœ… Yes
constBlockโŒ No
varFunctionโœ… Yes (Avoid using it)

Example:

let username: string = "Alice";
const PI: number = 3.14;
var country: string = "India"; // Not recommended in TypeScript

3๏ธโƒฃ Functions in TypeScript

TypeScript functions must define input and output types.

๐Ÿ”น Function with Parameters and Return Type

function addNumbers(a: number, b: number): number {
return a + b;
}
console.log(addNumbers(10, 20)); // Output: 30

โœ… Explanation:
โœ” a: number, b: number โ†’ Both parameters must be numbers.
โœ” : number โ†’ The function returns a number.

๐Ÿ”น Function with Optional Parameters

Use ? to make parameters optional.

function greet(name: string, age?: number): string {
if (age) {
return `Hello, ${name}. You are ${age} years old.`;
}
return `Hello, ${name}.`;
}
console.log(greet("John")); // Output: Hello, John.
console.log(greet("John", 25)); // Output: Hello, John. You are 25 years old.

4๏ธโƒฃ TypeScript Interfaces

An interface defines the structure of an object.

๐Ÿ”น Defining and Using Interfaces

interface Person {
name: string;
age: number;
isStudent?: boolean; // Optional property
}

let user: Person = { name: "Alice", age: 22 };
console.log(user.name); // Output: Alice

โœ… Why Use Interfaces?
โœ” Ensures objects follow a specific structure.
โœ” Helps in better code organization and error prevention.

5๏ธโƒฃ TypeScript Classes

Classes in TypeScript use object-oriented programming (OOP) principles like encapsulation, inheritance, and polymorphism.

๐Ÿ”น Defining a Class

class Car {
brand: string;
model: string;

constructor(brand: string, model: string) {
this.brand = brand;
this.model = model;
}

getDetails(): string {
return `Car: ${this.brand} ${this.model}`;
}
}

let myCar = new Car("Toyota", "Corolla");
console.log(myCar.getDetails()); // Output: Car: Toyota Corolla

โœ… Key Features:
โœ” constructor() initializes object properties.
โœ” getDetails() is a method that returns car details.

6๏ธโƒฃ TypeScript Arrays and Tuples

Arrays and tuples store multiple values.

๐Ÿ”น Array Declaration

let fruits: string[] = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Output: Apple

๐Ÿ”น Tuple Declaration

Tuples allow fixed types at specific positions.

let person: [string, number] = ["Alice", 25];
console.log(person[0]); // Output: Alice

โœ… Difference:
โœ” Array โ†’ Stores multiple values of the same type.
โœ” Tuple โ†’ Stores different types in a specific order.

7๏ธโƒฃ TypeScript Enums

Enums are used to define a set of named constants.

enum Direction {
Up = 1,
Down,
Left,
Right
}

let move: Direction = Direction.Up;
console.log(move); // Output: 1

โœ… Enums help in better readability when dealing with fixed values.

8๏ธโƒฃ TypeScript Union and Intersection Types

Union (|) allows multiple types, and Intersection (&) combines types.

๐Ÿ”น Union Type (Variable can hold multiple types)

let id: number | string;
id = 101; // Valid
id = "AB101"; // Also valid

๐Ÿ”น Intersection Type (Combining Interfaces)

interface A {
propA: string;
}

interface B {
propB: number;
}

type Combined = A & B;
let obj: Combined = { propA: "Hello", propB: 100 };

โœ… Why Use These?
โœ” Union types allow flexibility.
โœ” Intersection types combine multiple interfaces for more control.

9๏ธโƒฃ TypeScript Type Aliases

Aliases provide custom names for complex types.

type ID = number | string;
let userId: ID = 123; // Valid
userId = "ABC"; // Also valid

โœ… Aliases make code more readable and reusable.

๐Ÿ”Ÿ TypeScript Generics

Generics allow reusable code without specifying exact data types.

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

console.log(identity<string>("Hello")); // Output: Hello
console.log(identity<number>(100)); // Output: 100

โœ… Generics improve code reusability by allowing different data types.