Translate

New Live Courses

🚀 *Gen AI Engineer Telugu (Production Focused)*
🗓️ *Date:* 30th Sept 2026, 07:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/gr
👥 *Join WA Community:*
https://www.vlrt.in/gw
💡*Course Content:*
https://www.vlrt.in/ai
▶️ *Demo Videos:*
https://www.vlrt.in/gv

🚀 *Service now Admin/ Development (ITSM)FREE Demo in Telugu*
🗓️ *Date:* 30th Sept 2026, 08:00AM IST
📝 *Register Now!:*
https://www.vlrt.in/7r
👥 *Join WA Community:*
https://www.vlrt.in/7w
💡*Course Content:*
https://www.vlrt.in/7c
▶️ *Demo Videos:*
https://www.vlrt.in/7v

🚀 *Vulnerability Management Training Demo*
🗓️ *Date:* 30th Sept 2026, 09:00 AM IST
📝*Register Now!:*
https://www.vlrt.in/vr
👥 *Join Community:*
https://www.vlrt.in/cw
💡 *Course Content:*
https://www.vlrt.in/vc
▶️ *Demo Videos:*
https://www.vlrt.in/Vm

Saturday, 17 February 2024

What are Classes and Objects in Typescript ?66

 
What are Classes and Objects in Typescript

Classes and Objects in TypeScript

In TypeScript, classes serve as blueprints for creating objects. They encapsulate data (properties) and behavior (methods) related to a specific concept or entity.

Classes:

  • Defined using the class keyword and a name (e.g., class Person {}).

  • Can have properties (variables representing data) and methods (functions defining behavior).

  • Properties and methods can be public (accessible from anywhere), private (accessible only within the class), or protected (accessible within the class and subclasses).

Example:


TypeScript

class Person {
  // Public property
  name: string;

  // Private constructor (cannot be called directly)
  private constructor(name: string) {
    this.name = name;
  }

  // Public method
  greet(): void {
    console.log(`Hello, my name is ${this.name}`);
  }

  // Public static method (not associated with an instance)
  static create(name: string): Person {
    return new Person(name);
  }
}

Objects:

  • Created using the new keyword with the class name (e.g., const person = new Person("Alice")).

  • Represent instances of a class with access to its properties and methods.

  • Each object has its own set of property values and can invoke methods independently.

Example:


TypeScript

const alice = Person.create("Alice");
alice.greet(); // Output: "Hello, my name is Alice"

Inheritance:

  • Classes can inherit from other classes (called base classes) using the extends keyword.

  • Inherited classes get access to properties and methods of the base class, and can also add their own.

Example:


TypeScript

class Employee extends Person {
  company: string;

  constructor(name: string, company: string) {
    super(name); // Call base class constructor
    this.company = company;
  }

  introduce(): void {
    console.log(`Hi, I'm ${this.name} from ${this.company}`);
  }
}

const bob = new Employee("Bob", "Acme Corp");
bob.introduce(); // Output: "Hi, I'm Bob from Acme Corp"

Key Advantages:

  • Code organization: Classes group related data and behavior, promoting modularity and reusability.

  • Encapsulation: Data and implementation details are hidden within the class, improving maintainability and security.

  • Polymorphism: Subclasses can override inherited methods, providing flexible behavior based on the object type.

By effectively using classes and objects, you can create well-structured and maintainable TypeScript applications, organizing your code in a clear and reusable manner.


 What are Arrow Functions in Typescript ? 064

  What are Arrow Functions in Typescript ?


Arrow functions, also known as lambda functions, are a concise and readable way to define anonymous functions in TypeScript. They offer several advantages compared to traditional function expressions:

1. Syntax:

Arrow functions use the => operator instead of the function keyword, resulting in a more compact and elegant syntax.


TypeScript

// Traditional function expression
const sum = function(a: number, b: number): number {
  return a + b;
};

// Arrow function
const sum = (a: number, b: number): number => a + b;

2. Implicit return:

For single-line arrow functions, the explicit return statement is not necessary. The expression after the => is automatically returned.


TypeScript

const greet = (name: string) => `Hello, ${name}`;

3. Lexical this:

Arrow functions inherit the this binding from their surrounding context, unlike traditional functions which create their own this scope. This can be useful for preserving this in callback functions or event handlers.

4. Use in object properties:

Arrow functions can be directly used as object property values, simplifying object definition and avoiding the need for separate function names.


TypeScript

const person = {
  name: "Alice",
  greet: () => console.log(`Hello from ${this.name}`)
};

5. Use in class methods:

Arrow functions can be used as concise class methods, especially when they don't require their own this context.


TypeScript

class MyComponent {
  onClick = () => {
    // Access component properties using `this`
  };
}

When to use them:

  • Consider using arrow functions for short, anonymous functions, especially in callbacks, event handlers, and object properties.

  • Traditional function expressions might be preferred for complex functions requiring their own this binding or multi-line bodies.

Remember:

  • Arrow functions cannot be used as constructors or with the new keyword.

  • Use this binding cautiously in arrow functions within nested scopes or event handlers.

By understanding the syntax, benefits, and considerations of arrow functions, you can write more concise and readable TypeScript code while maintaining clarity and type safety.


What is Type Assertion in Typescript ?063

 What is Type Assertion in Typescript ?


Type assertion in TypeScript is a mechanism that allows you to tell the compiler to treat a value as having a specific type, even if the compiler might infer a different type. It's important to use type assertions with caution, as they can potentially bypass type safety checks and lead to runtime errors if used incorrectly.

Here's what you need to know about type assertions:

Purpose:

  • Overriding the inferred type: Sometimes, the compiler might not be able to accurately infer the type of a value due to complex logic or external factors. Type assertions allow you to explicitly tell the compiler what type you believe the value has.

  • Interacting with JavaScript code: When working with JavaScript libraries or frameworks that don't have proper type definitions, type assertions can be used to bridge the gap and provide type information to TypeScript.

Syntax:

There are two main ways to perform type assertions:

  1. Angle bracket syntax: <type>

  2. as keyword: value as type

Both methods achieve the same outcome, but the as keyword is generally preferred for readability.

Example:


TypeScript

// Get an element from the DOM (assumed to be an HTMLButtonElement)
const button = document.getElementById("myButton") as HTMLButtonElement;

// Access button properties now with type safety
button.disabled = true; // Valid since button now has the correct type

// Without type assertion:
// const button = document.getElementById("myButton");
// button.disabled = true; // This would cause a type error (button might not be an HTMLButtonElement)

Cautions:

  • Not a replacement for proper type safety: Type assertions don't change the actual value or its type at runtime. They only inform the compiler of your assumption about the type.

  • Potential runtime errors: If your type assertion is wrong, the program might still throw an error at runtime, even if the compiler doesn't detect it beforehand.

  • Use sparingly: Overuse of type assertions can make your code less readable and maintainable. Use them only when necessary and be confident about your reasoning.

Alternatives:

Consider these alternatives before resorting to type assertions:

  • Type casting: Similar to type assertions, but also performs runtime checks (can be slower).

  • Type guards: Functions that verify the type of a value at runtime (more explicit and safer).

  • Rewriting code: Refactoring your code to avoid the need for type assertions could be the best solution in some cases.

Remember, type assertions are a powerful tool, but use them judiciously and only when necessary to maintain type safety and clarity in your TypeScript code.