<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Lingaraj H U</title>
    <description>The latest articles on DEV Community by Lingaraj H U (@lingarajhu).</description>
    <link>https://dev.to/lingarajhu</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1831460%2Fca40de73-add9-4a7a-9862-a84924d93171.jpeg</url>
      <title>DEV Community: Lingaraj H U</title>
      <link>https://dev.to/lingarajhu</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/lingarajhu"/>
    <language>en</language>
    <item>
      <title>Simplifying Form Validation: React Hook Form vs Traditional Methods</title>
      <dc:creator>Lingaraj H U</dc:creator>
      <pubDate>Tue, 30 Jul 2024 13:48:15 +0000</pubDate>
      <link>https://dev.to/lingarajhu/simplifying-form-validation-react-hook-form-vs-traditional-methods-1a86</link>
      <guid>https://dev.to/lingarajhu/simplifying-form-validation-react-hook-form-vs-traditional-methods-1a86</guid>
      <description>&lt;p&gt;&lt;em&gt;Form validation is a crucial aspect of web development, ensuring data integrity and enhancing user experience. In the React ecosystem, we've seen a significant evolution in how we handle forms and their validation.&lt;/em&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;In this blog, we'll compare two approaches: traditional form validation and the modern React Hook Form library. &lt;/li&gt;
&lt;li&gt;By examining these methods side by side, we'll discover why React Hook Form has become a go-to solution for many developers.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Traditional Form Validation in React&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Let's start by looking at a traditional approach to form validation in React:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from "react";

const SimpleForm = () =&amp;gt; {

  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    password: "",
    // ... other fields
  });
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleChange = (e) =&amp;gt; {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value,
    });
  };

  const handleSubmit = (e) =&amp;gt; {
    e.preventDefault();
    setIsSubmitting(true);
    const newErrors = {};

    // Validation logic
    if (!formData.firstName) newErrors.firstName = "First Name is Required";

    if (!formData.lastName) newErrors.lastName = "Last Name is Required";

    if (!formData.email.match(/^\S+@\S+$/i)) newErrors.email = "Invalid email address";

    if (!formData.password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&amp;amp;])[A-Za-z\d@$!%*?&amp;amp;]{8,}$/)) newErrors.password = "Invalid password";

    // ... more validation rules

    if (Object.keys(newErrors).length &amp;gt; 0) {
      setErrors(newErrors);
      return;
    }

    // Submit form data
    try {
      const response = await simulateApiCall(formData);
      console.log("Success: ", response);
    } catch (error) {
      console.error(error);
      setError({ root: error.message });
    } finally {
      setIsSubmitting(false)
    }

  };

  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;input
        name="firstName"
        value={formData.firstName}
        onChange={handleChange}
      /&amp;gt;
      {errors.firstName &amp;amp;&amp;amp; &amp;lt;p&amp;gt;{errors.firstName}&amp;lt;/p&amp;gt;}

      &amp;lt;input
        name="lastName"
        value={formData.lastName}
        onChange={handleChange}
      /&amp;gt;
      {errors.lastName &amp;amp;&amp;amp; &amp;lt;p&amp;gt;{errors.lastName}&amp;lt;/p&amp;gt;}      

      &amp;lt;input
        name="email"
        value={formData.email}
        onChange={handleChange}
      /&amp;gt;
      {errors.email &amp;amp;&amp;amp; &amp;lt;p&amp;gt;{errors.email}&amp;lt;/p&amp;gt;}


      &amp;lt;input
        type="password"
        name="password"
        value={formData.password}
        onChange={handleChange}
      /&amp;gt;
      {errors.password &amp;amp;&amp;amp; &amp;lt;p&amp;gt;{errors.password}&amp;lt;/p&amp;gt;}

      {/* More form fields */}

      &amp;lt;button type="submit" disabled={isSubmitting}&amp;gt;
        {isSubmitting ? "Submitting..." : "Submit"}
      &amp;lt;/button&amp;gt;
    &amp;lt;/form&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;In this traditional approach&lt;/strong&gt; &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;We manage form state and error state separately using the &lt;code&gt;useState&lt;/code&gt; hook. &lt;/li&gt;
&lt;li&gt;We manually handle changes to form fields and implement custom validation logic in the &lt;code&gt;handleSubmit&lt;/code&gt; function. 

&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;While this works, it involves a lot of boilerplate code and can become cumbersome for larger forms.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Enter React Hook Form&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Now, let's see how we can achieve the same result using React Hook Form:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;Installation&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install react-hook-form
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";

// useForm is the hook which is given by react-hook-form
import { useForm } from "react-hook-form";

const ReactHookForm = () =&amp;gt; {

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors, isSubmitting },
  } = useForm();

  const onSubmit = (data) =&amp;gt; {
    // Submit form data
    try {
      const response = await simulateApiCall(formData);
      console.log("Success: ", response);
    } catch (error) {
      console.error(error);
      setError({ root: error.message });
    }
  };

  return (
    &amp;lt;form onSubmit={handleSubmit(onSubmit)}&amp;gt;
      &amp;lt;input
        {...register("firstName", { required: "First Name is required" 
        })}
      /&amp;gt;

      {errors.firstName &amp;amp;&amp;amp; &amp;lt;p&amp;gt;{errors.firstName.message}&amp;lt;/p&amp;gt;}

      &amp;lt;input
        {...register("lastName", { required: "Last Name is required" 
        })}
      /&amp;gt;

      {errors.lasttName &amp;amp;&amp;amp; &amp;lt;p&amp;gt;{errors.lasttName.message}&amp;lt;/p&amp;gt;}      

      &amp;lt;input
        {...register("email", {
          required: "Email is required",
          pattern: { value: /^\S+@\S+$/i, message: "Invalid email address" }
        })}
      /&amp;gt;

      {errors.email &amp;amp;&amp;amp; &amp;lt;p&amp;gt;{errors.email.message}&amp;lt;/p&amp;gt;}

      &amp;lt;input
        {...register("password", { required: "First Name is required",
         pattern: { value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&amp;amp;])[A-Za-z\d@$!%*?&amp;amp;]{8,}$/, message: "Invalid password"}
        })}
      /&amp;gt;

      {errors.firstName &amp;amp;&amp;amp; &amp;lt;p&amp;gt;{errors.firstName.message}&amp;lt;/p&amp;gt;}      

      {/* More form fields */}

      &amp;lt;button type="submit" disabled={isSubmitting}&amp;gt;
        {isSubmitting ? "Submitting..." : "Submit"}
      &amp;lt;/button&amp;gt;

    &amp;lt;/form&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;The Simplicity of React Hook Form&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Reduced Boilerplate: React Hook Form eliminates the need for manual state management. No more &lt;code&gt;useState&lt;/code&gt; for form data and errors.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Declarative Validation: Instead of writing imperative validation logic, we declare our validation rules right in the &lt;code&gt;register&lt;/code&gt; function. This makes the code more readable and maintainable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Automatic Error Handling: React Hook Form automatically tracks errors and provides them through the &lt;code&gt;errors&lt;/code&gt; object, eliminating the need for manual error state management.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Performance: By leveraging uncontrolled components, React Hook Form minimizes re-renders, leading to better performance, especially for large forms.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Easy Integration: The &lt;code&gt;register&lt;/code&gt; function seamlessly integrates with your existing input elements, requiring minimal changes to your &lt;code&gt;JSX&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Built-in Validation: Common validation rules like &lt;code&gt;required&lt;/code&gt;, &lt;code&gt;min&lt;/code&gt;, &lt;code&gt;max&lt;/code&gt;, &lt;code&gt;pattern&lt;/code&gt; are built-in, reducing the need for custom validation functions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;TypeScript Support: React Hook Form provides excellent TypeScript support out of the box, enhancing type safety in your forms.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://github.com/lingarajhu/react-hook-form/blob/main/src/components/ReactHookForm.tsx" rel="noopener noreferrer"&gt;To understand the how to handle &lt;code&gt;react-hook-form&lt;/code&gt; in &lt;code&gt;typescript&lt;/code&gt; with more input fileds&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;While traditional form handling in React gives you fine-grained control, it often leads to verbose code that can be hard to maintain.&lt;/em&gt; &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;em&gt;React Hook Form simplifies this process significantly, providing a more declarative and efficient way to handle forms and their validation.&lt;/em&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Thank you for reading... hope you learnt something new today :)&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Understanding Enums in TypeScript.</title>
      <dc:creator>Lingaraj H U</dc:creator>
      <pubDate>Fri, 26 Jul 2024 15:12:50 +0000</pubDate>
      <link>https://dev.to/lingarajhu/understanding-enums-in-typescript-1259</link>
      <guid>https://dev.to/lingarajhu/understanding-enums-in-typescript-1259</guid>
      <description>&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Have you ever found yourself juggling multiple values in your code, wishing there was a more organized way to manage them?&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Imagine having a list of predefined options that are both human-readable and machine-understandable. This is where &lt;code&gt;enums&lt;/code&gt; come to the rescue!!!&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Enums, short for enumerations, are a powerful feature in TypeScript that allows you to define a set of named constants. They're particularly useful when you have a fixed set of values that a variable can take.
&lt;/h3&gt;

&lt;p&gt;Let's dive into &lt;code&gt;enums&lt;/code&gt; and see how they can make your code more readable and maintainable.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Here's a simple &lt;code&gt;enum&lt;/code&gt; definition:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Basic &lt;code&gt;enum&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Direction {
  North,
  East,
  South,
  West
}

// Using the enum
let myDirection: Direction = Direction.North;
console.log(myDirection); // Output: 0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;By default, &lt;code&gt;enums&lt;/code&gt; are number-based, starting from 0. But you can customize this:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Direction {
  North = 1,
  East,  // 2
  South, // 3
  West   // 4
}

// if you initialize first variable by a particular value then
// the next variable will maintain the order of value 
// assigned to first variable 

enum Direction {
  North = 100,
  East,  // 101
  South, // 102
  West   // 103
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;String Enums&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;TypeScript also supports string &lt;code&gt;enums&lt;/code&gt;, which are more descriptive&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

let myFavoriteColor: Color = Color.Blue;
console.log(myFavoriteColor); // Output: "BLUE"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Heterogeneous Enums&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can mix string and numeric members, but it's generally not recommended:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Mixed {
  Number = 1,
  String = "String"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Reverse Mappings
Numeric &lt;code&gt;enums&lt;/code&gt; come with reverse mappings, allowing you to get the enum member name from its value:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum Weekday {
  Monday,
  Tuesday,
  Wednesday
}

console.log(Weekday[0]); // Output: "Monday"

enum Direction {
  North = 100,
  East,  // 101
  South, // 102
  West   // 103
}

console.log(Direction[101]); // output: "East"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  When to Use Enums?
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Enums come in handy in several scenarios:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Representing a fixed set of options:&lt;/strong&gt; Like days of the week, card suits, or HTTP status codes.&lt;br&gt;
&lt;strong&gt;Improving code readability:&lt;/strong&gt; Instead of using magic numbers or strings, enums provide meaningful names.&lt;br&gt;
&lt;strong&gt;Type safety:&lt;/strong&gt; TypeScript ensures you only use valid enum values, catching errors at compile-time.&lt;/p&gt;

&lt;h4&gt;
  
  
  Some common use cases for enums include:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Defining a set of error codes or status codes.&lt;/li&gt;
&lt;li&gt;Representing a set of colors, sizes, or other categorical values.&lt;/li&gt;
&lt;li&gt;Defining a set of roles or permissions in an application.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Here's a practical example:
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Payment Status Enum
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;In a payment processing system, we need to handle different payment statuses, such as "Pending", "Success", "Failed", etc. We can define an &lt;code&gt;enum&lt;/code&gt; to represent these statuses:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum PaymentStatus {
  Pending = 'pending',
  Success = 'success',
  Failed = 'failed',
  Refunded = 'refunded'
}

// Using the Enum:
// Now, let's use this `enum` in a payment processing function:

function processPayment(status: PaymentStatus) {
  switch (status) {

    case PaymentStatus.Pending:
      // Handle pending payment
      break;

    case PaymentStatus.Success:
      // Handle successful payment
      break;

    case PaymentStatus.Failed:
      // Handle failed payment
      break;

    case PaymentStatus.Refunded:
      // Handle refunded payment
      break;

    default:
      throw new Error('Invalid payment status');

  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Enums in TypeScript offer a clean way to define a set of named constants. They enhance code readability, provide type safety, and are especially useful when working with fixed sets of values.&lt;/li&gt;
&lt;li&gt;As you progress in your TypeScript journey, you'll find enums to be a valuable tool in your programming toolkit.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Thank you for reading... Hope you learnt something new today :)&lt;/strong&gt; &lt;/p&gt;

</description>
      <category>typescript</category>
      <category>webdev</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>My Journey with Classes and Objects in TypeScript: Lessons Learned!!!</title>
      <dc:creator>Lingaraj H U</dc:creator>
      <pubDate>Thu, 25 Jul 2024 13:19:03 +0000</pubDate>
      <link>https://dev.to/lingarajhu/my-journey-with-classes-and-objects-in-typescript-lessons-learned-3o69</link>
      <guid>https://dev.to/lingarajhu/my-journey-with-classes-and-objects-in-typescript-lessons-learned-3o69</guid>
      <description>&lt;h2&gt;
  
  
  When I first started with TypeScript, classes and objects seemed daunting. But as I dug deeper, I discovered how powerful they can be. Let me share what I've learned along the way.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;The Building Blocks: Basic Class Structure.
I remember my first TypeScript class - it was a simple Car class:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Car {
  make: string; // this is how you define the properties
  model: string;

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

  // A method to simulate driving the car
  drive() {
    console.log(`Cruising down the highway in my ${this.make} ${this.model}. What a ride!`);
  }
}

// Let's create new instance of the above class car.
const myDreamCar = new Car('Tesla', 'Model S');
myDreamCar.drive(); // Vrooom!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This basic structure became my go-to template for creating objects. It's amazing how much you can do with just properties and methods!&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Keeping Secrets: Access Modifiers
As my projects grew, I needed to protect certain data. That's when I discovered access modifiers:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class PiggyBank {
  private savings: number; // Our secret stash!

  constructor(initialAmount: number) {
    this.savings = initialAmount;
  }

  // Public method to add money
  public deposit(amount: number) {
    this.savings += amount;
    console.log(`Cha-ching! Deposited ${amount}. New balance: ${this.savings}`);
  }

  // Protected method for inheritance purposes the only way to access this 
  // protected method by implementing the child of this class.

  protected getBalance() {
    return this.savings;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using private and protected members felt like adding a security system to my code. No more accidental tampering!&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The Family Tree: Inheritance
Inheritance clicked for me when I thought about it in terms of a family tree:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance}m. They're on the go!`);
  }
}

class Dog extends Animal {
  bark() {
    console.log(`${this.name} says: Woof! Woof! Where's the mailman?`);
  }
}

// Let's create a furry friend!
const myPup = new Dog('Buddy');
myPup.bark();
myPup.move(10); // Buddy's on a mission!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It was like creating a family of classes, with each child inheriting traits from its parent. Pretty cool, right?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Making Promises: Interfaces and Classes
Interfaces helped me set clear expectations for my classes:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Vechicle {
  start(): void;
  stop(): void;
}

// when a class implements the interface you must define 
// the methods which are declared in that interface.

class Car implements Vechicle {
  start() {
    console.log('Engine purrs to life. Ready for adventure!');
  }
  stop() {
    console.log('Parking brake on. Journey complete!');
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's like making a promise: if a class implements an interface, it's guaranteed to have certain methods.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The Blueprint: Abstract Classes
Abstract classes were a game-changer for creating flexible yet structured code:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// An abstract class is a blueprint for other classes.

// It can't be instantiated directly but can be inherited from.

abstract class Shape {

  // An abstract method doesn't have an implementation in the abstract class.

  // It must be implemented by any concrete (non-abstract) derived class.

  abstract getArea(): number; // abstract method

  // A concrete method in an abstract class has an implementation
  // and can be used by all derived classes.

  printArea() {
    console.log(`This shape covers ${this.getArea()} square units. Neat!`);
  }

}

// Circle is a concrete class that extends the abstract Shape class

class Circle extends Shape {

  // The 'private' keyword makes radius accessible only within this class

  constructor(private radius: number) {

    // 'super()' calls the constructor of the parent class (Shape)

    // It's required when extending a class, even if the parent class
    // doesn't have an explicit constructor

    super();

  }

  // This is the implementation of the abstract method from Shape

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

}

// We can create an instance of Circle, but not of Shape

const frisbee = new Circle(5);

// This calls printArea() from Shape, which in turn calls getArea() from Circle

frisbee.printArea();
// Outputs: This shape covers 78.53981633974483 square units. Neat!
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Learning about classes and objects in TypeScript has been a journey. Each concept opened up new possibilities in my coding adventures. Whether you're building a simple app or a complex system, these tools can help you write cleaner, more organized code. &lt;/p&gt;

&lt;p&gt;Hope you learnt something new....!!!!. thank you reading till the end :)&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>beginners</category>
      <category>programming</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Mastering TypeScript Functions: Your Guide to Stronger, Safer Code</title>
      <dc:creator>Lingaraj H U</dc:creator>
      <pubDate>Wed, 24 Jul 2024 17:14:56 +0000</pubDate>
      <link>https://dev.to/lingarajhu/mastering-typescript-functions-your-guide-to-stronger-safer-code-3i1g</link>
      <guid>https://dev.to/lingarajhu/mastering-typescript-functions-your-guide-to-stronger-safer-code-3i1g</guid>
      <description>&lt;h2&gt;
  
  
  TypeScript enhances JavaScript functions with powerful type-checking capabilities. Let's explore the key features that make TypeScript functions an essential tool for modern web development.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Basic Function Syntax:
TypeScript allows you to specify parameter types and return types, making your function's intentions clear.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function greet(name: string): string {
  return `Hello, ${name}!`;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function takes a string parameter and guarantees a string return value.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Arrow Functions:
Arrow functions provide a concise syntax and lexical scoping of '&lt;a href="https://www.typescriptlang.org/docs/handbook/2/classes.html#arrow-functions" rel="noopener noreferrer"&gt;this&lt;/a&gt;'.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const multiply = (a: number, b: number): number =&amp;gt; a * b;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we define a function that takes two numbers and returns their product.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Optional and Default Parameters: 
TypeScript lets you define optional parameters and set default values.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createUser(name: string, age?: number, role: string = 'user') {
  // Implementation
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, 'age' is optional, and 'role' has a default value of 'user'.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Rest Parameters:
&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters" rel="noopener noreferrer"&gt;Rest parameters&lt;/a&gt; allow a function to accept an indefinite number of arguments as an array.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sum(...numbers: number[]): number {
  return numbers.reduce((total, num) =&amp;gt; total + num, 0);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function can take any number of numeric arguments and return their sum.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Function Overloading:
Function overloading allows you to define multiple function signatures for varied behavior.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function processInput(input: string): string;
function processInput(input: number): number;
function processInput(input: string | number): string | number {
  if (typeof input === 'string') {
    return input.toUpperCase();
  } else {
    return input * 2;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This function can handle both string and number inputs, with different behavior for each.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Generic Functions:
&lt;a href="https://www.typescriptlang.org/docs/handbook/2/generics.html" rel="noopener noreferrer"&gt;Generics&lt;/a&gt; allow you to create flexible, reusable functions that work with multiple types.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function firstElement&amp;lt;T&amp;gt;(arr: T[]): T | undefined {
  return arr[0];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This generic function can work with arrays of any type and return the first element of that type.&lt;/p&gt;

&lt;p&gt;TypeScript functions provide a robust foundation for building complex applications. By leveraging these features, you can write more expressive, safer, and self-documenting code.&lt;/p&gt;

&lt;p&gt;Remember: The goal is not just to add types, but to use TypeScript's features to create more reliable and maintainable code structures.&lt;/p&gt;

&lt;p&gt;I hope you learned something new in this short blog. :)&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Types vs Interfaces in TypeScript: Which Should You Choose?</title>
      <dc:creator>Lingaraj H U</dc:creator>
      <pubDate>Wed, 24 Jul 2024 11:15:14 +0000</pubDate>
      <link>https://dev.to/lingarajhu/types-vs-interfaces-in-typescript-which-should-you-choose-334g</link>
      <guid>https://dev.to/lingarajhu/types-vs-interfaces-in-typescript-which-should-you-choose-334g</guid>
      <description>&lt;p&gt;Are you new to TypeScript and wondering about the difference between types and interfaces? Let's break it down with some cool examples!&lt;/p&gt;

&lt;h2&gt;
  
  
  🔹 Types: The Swiss Army Knife.
&lt;/h2&gt;

&lt;p&gt;Types in TypeScript are super flexible. They're like the Swiss Army knife of type definitions.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Define an object type for a superhero
type Superhero = {
  name: string;
  power: string;
  flyable?: boolean;  // Optional property
};

// Create a union type for a limited set of color options
type Color = "red" | "blue" | "green";

// Define a function type for mathematical operations
type MathFunction = (x: number, y: number) =&amp;gt; number;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  🔹 Interfaces: The Blueprint
&lt;/h2&gt;

&lt;p&gt;Interfaces are like blueprints for objects. They're great for defining the structure of classes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Define an interface for a vehicle
interface Vehicle {
  brand: string;
  speed: number;
  accelerate(): void;  // Method signature
}

// Implement the Vehicle interface in a Car class
class Car implements Vehicle {
  brand: string;
  speed: number;

  constructor(brand: string) {
    this.brand = brand;
    this.speed = 0;
  }

  // Implement the accelerate method
  accelerate() {
    this.speed += 10;
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  🔥 Key Differences:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;Union Types: Only possible with 'type'
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Union type (only possible with 'type')
type Status = "pending" | "approved" | "rejected";

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Extending: Both can extend, but interfaces are more natural for OOP
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Extending an interface
interface Animal {
  name: string;
}
interface Dog extends Animal {
  bark(): void;
}

// Extending a type
type Shape = {
  color: string;
}
type Circle = Shape &amp;amp; {
  radius: number;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Declaration Merging: Only interfaces can be reopened to add new properties.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Declaration merging (only possible with interfaces)
interface Book {
  title: string;
}
interface Book {
  author: string;
}
// Now Book has both title and author properties
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;💡 Dev Tip: Use interfaces for objects and classes, and types for functions, unions, and complex types.&lt;/p&gt;

&lt;p&gt;Remember, whether you use types or interfaces, TypeScript has got your back in catching errors before runtime!&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
