0% found this document useful (0 votes)
2 views6 pages

TypeScript Advanced

The document provides an overview of key TypeScript concepts including Enums, Interfaces, Classes, Generics, Modules, Decorators, Type Narrowing, and Type Guards. Each concept is explained with examples to illustrate their usage and benefits in writing cleaner and more maintainable code. The conclusion emphasizes the importance of these features in structuring TypeScript applications effectively.

Uploaded by

suyashkunde222
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

TypeScript Advanced

The document provides an overview of key TypeScript concepts including Enums, Interfaces, Classes, Generics, Modules, Decorators, Type Narrowing, and Type Guards. Each concept is explained with examples to illustrate their usage and benefits in writing cleaner and more maintainable code. The conclusion emphasizes the importance of these features in structuring TypeScript applications effectively.

Uploaded by

suyashkunde222
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# **TypeScript

## **1. Enums** – **A Way to Give Names to Values**

Think of an **enum** as a way to store a group of related values and give them meaningful names.
Instead of using numbers or strings directly, we use enums to make code more readable and
manageable.

### **Example: Days of the Week Enum**

enum Days {

Sunday,

Monday,

Tuesday,

Wednesday,

Thursday,

Friday,

Saturday

let today: Days = [Link];

[Link](today);

By default, the first value starts from **0**. You can also assign custom values:

```typescript

enum Status {

Success = 200,

NotFound = 404,

Error = 500

[Link]([Link]);
## **2. Interfaces** – **A Blueprint for Objects**

An **interface** defines the shape of an object. It ensures that objects follow a certain structure. Think
of it as a contract—if an object follows the interface, it must have all the required properties.

### **Example: Defining a Person Interface**

interface Person {

name: string;

age: number;

let user: Person = {

name: "John Doe",

age: 30

};

[Link]([Link]);

Here, every object of type `Person` **must** have `name` (string) and `age` (number).

Interfaces can also have **optional properties**:

interface Car {

brand: string;

model: string;

year?: number; // Optional

let myCar: Car = {

brand: "Toyota",

model: "Corolla"

}; // 'year' is optional, so this is valid.

## **3. Classes** – **Blueprint for Creating Objects**

A **class** is like a template for creating objects with properties and methods. It helps organize code
better.
### **Example: A Simple Class in TypeScript**

class Animal {

name: string;

constructor(name: string) {

[Link] = name;

makeSound() {

[Link]([Link] + " makes a sound!");

let dog = new Animal("Dog");

[Link]();

### **Class with Inheritance (Extending a Class)**

class Dog extends Animal {

bark() {

[Link]([Link] + " barks!");

let myDog = new Dog("Buddy");

[Link]();```

## **4. Generics** – **A Way to Make Code Reusable**

Generics allow us to write code that works with **any data type** instead of being fixed to a single
type.

### **Example: Generic Function**

function identity<T>(value: T): T {

return value;

[Link](identity(10));

[Link](identity("Hello"));
Here, `<T>` is a **placeholder** for any type.

### **Example: Generic Class**

class Box<T> {

content: T;

constructor(content: T) {

[Link] = content;

let numberBox = new Box<number>(100);

let stringBox = new Box<string>("Hello");

[Link]([Link]);

[Link]([Link]); //

This makes the class flexible—it can store numbers, strings, or any other type.

## **5. Modules** – **Organizing Code into Files**

Modules help us split code into multiple files and **reuse** functions, classes, or interfaces across
different files.

### **Example: Exporting from a Module ([Link])**

export function add(a: number, b: number): number {

return a + b;

### **Importing the Module in Another File**

import { add } from "./mathUtils";

[Link](add(5, 10));

Here, `export` allows a function to be used in another file, and `import` brings it into a new file.

## **6. Decorators** – **Adding Extra Behavior to Classes and Methods**


Decorators allow us to **modify** classes, methods, or properties dynamically. They are **like
annotations** that add extra functionality.

### **Example: Class Decorator**

function logClass(target: Function) {

[Link]("Class created: " + [Link]);

@logClass

class Car {

constructor() {

[Link]("Car object created!");

let myCar = new Car();

## **7. Type Narrowing** – **Making Code Smarter by Identifying Types**

TypeScript can **automatically detect** and "narrow" down types based on conditions.

### **Example: Using `typeof`**

function printValue(value: number | string) {

if (typeof value === "string") {

[Link]("It's a string: " + [Link]());

} else {

[Link]("It's a number: " + (value * 2));

printValue(10);

printValue("hello");

Here, TypeScript automatically detects if `value` is a string or number.


## **8. Type Guards** – **Ensuring Correct Type Usage**

A **Type Guard** is a function that checks if a variable is a specific type.

### **Example: Using a Type Guard Function**

interface Dog {

bark: () => void;

interface Cat {

meow: () => void;

function isDog(animal: Dog | Cat): animal is Dog {

return (animal as Dog).bark !== undefined;

let pet: Dog = { bark: () => [Link]("Woof!") };

if (isDog(pet)) {

[Link]();

# **Conclusion**

- **Enums** are used for naming related values.

- **Interfaces** define object structure.

- **Classes** help create reusable object blueprints.

- **Generics** allow flexibility in handling different data types.

- **Modules** help organize and share code.

- **Decorators** enhance classes and methods dynamically.

- **Type Narrowing** helps TypeScript understand types automatically.

- **Type Guards** ensure safe type checking in runtime.

These concepts help **write cleaner, more structured, and maintainable** TypeScript code! 🚀

You might also like