Type Script Features

Type Script Features

# Exploring TypeScript Features: A Comprehensive Guide

As developers, we continually seek ways to enhance the robustness and maintainability of our code. TypeScript, a superset of JavaScript, provides a powerful set of features that contribute to a more structured and scalable development experience. In this article, we'll delve into key TypeScript features and provide practical examples to illustrate their usage.

  1. Interfaces: Interfaces define the structure of objects, ensuring they adhere to a specific contract. For instance, consider a Person interface:


interface Person {
  name: string;
  age: number;
}

const person: Person = {
  name: "John",
  age: 30,
};        

2. Namespaces: - Namespaces in TypeScript allow us to organize code into logical groups, preventing naming conflicts. Let's take a look at a simple example within a Geometry namespace.

namespace Geometry {
  export const PI = 3.14;

  export function calculateCircumference(radius: number): number {
    return 2 * PI * radius;
  }
}

console.log(Geometry.calculateCircumference(5)); // Output: 31.4        


3. Generics:-- Generics enable the creation of flexible and reusable components. Here's a generic identity function.

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

const result: number = identity(42);
const value: string = identity("hello");        

4. Abstract Classes:- Abstract classes provide a foundation for other classes and can contain abstract methods. Consider an abstract Shape class:

abstract class Shape {
  abstract calculateArea(): number;
}

class Circle extends Shape {
  constructor(private radius: number) {
    super();
  }

  calculateArea(): number {
    return Math.PI * this.radius ** 2;
  }
}

const circle = new Circle(5);
console.log(circle.calculateArea()); // Output: 78.54        

5. Access Modifiers:- Access modifiers such as private, protected, and public control the visibility of class members. In the example below, the speed property is private:

class Car {
  private speed: number;

  constructor() {
    this.speed = 0;
  }

  accelerate(): void {
    this.speed += 10;
  }

  getSpeed(): number {
    return this.speed;
  }
}

const myCar = new Car();
myCar.accelerate();
console.log(myCar.getSpeed()); // Output: 10        

6. Optionals:- Optionals allow the definition of properties that may or may not be present. Here's an example with an optional author property in a Book interface:

interface Book {
  title: string;
  author?: string;
}

const book1: Book = {
  title: "The TypeScript Book",
};

const book2: Book = {
  title: "JavaScript Fundamentals",
  author: "John Doe",
};        


7. Function Overloading:-- Function overloading allows defining multiple function signatures for a single function. TypeScript will resolve the correct signature based on the number and types of arguments provided during the function call.

function greet(name: string): string;
function greet(name: string, age: number): string;

function greet(name: string, age?: number): string {
  if (age !== undefined) {
    return `Hello, ${name}! You are ${age} years old.`;
  } else {
    return `Hello, ${name}!`;
  }
}

console.log(greet("John")); // Output: Hello, John!
console.log(greet("Jane", 25)); // Output: Hello, Jane! You are 25 years old.
        

8. Decorators:- Decorators are a way to add metadata to classes, methods, or properties in TypeScript. They are extensively used in frameworks like Angular to enhance and modify the behavior of classes and methods.

function log(target: any, key: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

  descriptor.value = function (...args: any[]) {
    console.log(`Calling ${key} with arguments: ${JSON.stringify(args)}`);
    const result = originalMethod.apply(this, args);
    console.log(`Method ${key} returned: ${JSON.stringify(result)}`);
    return result;
  };

  return descriptor;
}

class Calculator {
  @log
  add(a: number, b: number): number {
    return a + b;
  }
}

const calculator = new Calculator();
console.log(calculator.add(2, 3)); // Output: Calling add with arguments: [2,3]  Method add returned: 5
        

9. Type Utilities: TypeScript provides utility types like Partial, Pick, and Record that simplify common type manipulations. These utilities enhance code readability and maintainability by providing expressive ways to work with types.

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

type PartialUser = Partial<User>;
type RecordUser = Record<"id" | "name", string>;

const partialUser: PartialUser = { name: "John" };
const recordUser: RecordUser = { id: "1", name: "Jane" };
        





要查看或添加评论,请登录

Sanjay Chahal的更多文章

  • Pomodoro Technique

    Pomodoro Technique

    In today's fast-paced world, staying focused and productive can be a real challenge. With constant distractions and an…

  • Methods to handle app crashes in production?

    Methods to handle app crashes in production?

    Maintaining a positive user experience and ensuring the stability of your application is a critical aspect of software…

  • Dependency Inversion

    Dependency Inversion

    Unlocking Modular Excellence: The Power of Dependency Inversion Principle As software development evolves, the…

  • Mastering Swift Enums: Unlocking the Power of Enumeration

    Mastering Swift Enums: Unlocking the Power of Enumeration

    What is an enum in Swift, and why would you use it? An enum is a data type that defines a set of named values. It's…

    1 条评论
  • The Flyweight pattern

    The Flyweight pattern

    The Flyweight pattern is used to optimize memory usage or computational resources by sharing common parts of objects…

    1 条评论
  • Proxy Design Pattern and Use-cases in IOS App development

    Proxy Design Pattern and Use-cases in IOS App development

    The Proxy Design Pattern provides a proxy class that acts as an intermediary for controlling access to the real object.…

    1 条评论
  • Adapter Design Pattern

    Adapter Design Pattern

    The Adapter Design Pattern is a structural design pattern that allows objects with incompatible interfaces to work…

    2 条评论
  • The Decorator Pattern

    The Decorator Pattern

    The Decorator pattern is a structural design pattern that allows you to add behaviour to individual objects, either…

    1 条评论
  • How Fastlane can help to automate the app development process

    How Fastlane can help to automate the app development process

    Fastlane is a popular open-source toolset used by iOS developers to automate various tasks in the app development…

  • Transitioning from a junior iOS developer to a senior iOS developer

    Transitioning from a junior iOS developer to a senior iOS developer

    Transitioning from a junior iOS developer to a senior iOS developer requires a combination of technical skills…

    1 条评论

社区洞察

其他会员也浏览了