<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ generics - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ generics - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 14 May 2026 11:47:35 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/generics/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Generics in Java – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ In your Java program, you might have encountered the dreaded ClassCastException at runtime while working with different types of objects such as Integer, String, and so on. This error is mostly caused by casting an object to the wrong data type.  In ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/generics-in-java/</link>
                <guid isPermaLink="false">66ba1abbf1ac6be9964fe743</guid>
                
                    <category>
                        <![CDATA[ generics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jul 2024 18:57:24 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/safety.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In your Java program, you might have encountered the dreaded <code>ClassCastException</code> at runtime while working with different types of objects such as Integer, String, and so on. This error is mostly caused by casting an object to the wrong data type. </p>
<p>In this article, you'll learn about generics and see how they can help address this problem.</p>
<p>##Why Do We Need Generics?</p>
<p>Let's begin with a simple example. We will first add different types of objects to an <code>ArrayList</code>. Next, we will try to retrieve them and print their values.</p>
<pre><code class="lang-java">List list = <span class="hljs-keyword">new</span> ArrayList();

list.add(<span class="hljs-string">"Hello"</span>);

String str = (String) list.get(<span class="hljs-number">0</span>);

System.out.println(<span class="hljs-string">"String: "</span> + str);
</code></pre>
<p>As you can see, we have added a <code>String</code> object to the <code>ArrayList</code>. Since we are the ones who have written the code, we know what type of object the element represents, but, the compiler does not know that. So, when we attempt to retrieve the value from the list, we get back an <code>Object</code> and we have to perform an explicit casting.</p>
<pre><code class="lang-java">list.add(<span class="hljs-number">123</span>);

String number = (String) list.get(<span class="hljs-number">1</span>);

System.out.println(<span class="hljs-string">"Number: "</span> + number);
</code></pre>
<p>If we add an <code>Integer</code> to the same list and try to fetch the value, we will get a <code>ClassCastException</code> because an Integer object cannot be cast to a String.</p>
<p>By using Generics, we can solve both problems discussed above. Let's see how.</p>
<p>First, we need to use the diamond operator and narrow the type of object held in this list. We need to mention the object type explicitly within the diamond operator. This will enforce a compile-time check, so you no longer have to perform explicit casting. You will also be able to eliminate the <code>ClassCastException</code>.</p>
<pre><code class="lang-java">List&lt;String&gt; list = <span class="hljs-keyword">new</span> ArrayList();

list.add(<span class="hljs-string">"Hello"</span>);

String str = list.get(<span class="hljs-number">0</span>); <span class="hljs-comment">// No need for explicit casting</span>

System.out.println(<span class="hljs-string">"String: "</span> + str);

list.add(<span class="hljs-number">123</span>); <span class="hljs-comment">// Throws compile-time error</span>
</code></pre>
<p>##Naming Conventions for Type Parameters</p>
<p>In the previous example, you saw that the use of <code>List&lt;String&gt;</code> narrowed the type of the object that the list could hold. Check out the following example of a <code>Box</code> class and how it works with different types of data.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span>&lt;<span class="hljs-title">T</span>&gt; </span>{
    <span class="hljs-keyword">private</span> T value;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setValue</span><span class="hljs-params">(T value)</span> </span>{
        <span class="hljs-keyword">this</span>.value = value;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">getValue</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> value;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Box&lt;String&gt; stringBox = <span class="hljs-keyword">new</span> Box&lt;&gt;();
        stringBox.setValue(<span class="hljs-string">"Hello, world!"</span>);
        System.out.println(stringBox.getValue());

        Box&lt;Integer&gt; integerBox = <span class="hljs-keyword">new</span> Box&lt;&gt;();
        integerBox.setValue(<span class="hljs-number">123</span>);
        System.out.println(integerBox.getValue());
    }
}
</code></pre>
<p>Note how the <code>Box&lt;T&gt;</code> class is declared. Here, the <code>T</code> is a type parameter, indicating that the <code>Box</code> class can work with any object of that type. The same is illustrated in the main method where an instance of <code>Box&lt;String&gt;</code> and <code>Box&lt;Integer&gt;</code> are both allowed to be created, thus ensuring type safety.</p>
<p>As per the <a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/generics/types.html">official documentation</a>:</p>
<blockquote>
<p>By convention, type parameter names are single, uppercase letters.   </p>
<p>The most commonly used type parameter names are:  </p>
<p>E - Element (used extensively by the Java Collections Framework)<br>K - Key<br>N - Number<br>T - Type<br>V - Value<br>S,U,V etc. - 2nd, 3rd, 4th types</p>
</blockquote>
<p>Let's take a look at how we can write a generic method. Below is the convention:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;T&gt; <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">printArray</span><span class="hljs-params">(T[] inputArr)</span> </span>{
    <span class="hljs-keyword">for</span> (T element : inputArr) {
        System.out.print(element + <span class="hljs-string">" "</span>);
    }
    System.out.println();
}
</code></pre>
<p>Here, we take an array of any type and print its elements. Note that you need to specify the generic type parameter <code>T</code> in the angle brackets <code>&lt;&gt;</code> before the return type of the method. The method body iterates over the array that we have passed as a parameter, of any type <code>T</code>, and prints each element.</p>
<pre><code class="lang-java"> <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        <span class="hljs-comment">// Create different arrays of type Integer, Double and Character</span>
        Integer[] intArr = {<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>};
        Double[] doubleArr = {<span class="hljs-number">1.1</span>, <span class="hljs-number">2.2</span>, <span class="hljs-number">3.3</span>, <span class="hljs-number">4.4</span>, <span class="hljs-number">5.5</span>};
        Character[] charArr = {<span class="hljs-string">'H'</span>, <span class="hljs-string">'E'</span>, <span class="hljs-string">'L'</span>, <span class="hljs-string">'L'</span>, <span class="hljs-string">'O'</span>};

        System.out.println(<span class="hljs-string">"Integer array contains:"</span>);
        printArray(intArr);   <span class="hljs-comment">// pass an Integer array</span>

        System.out.println(<span class="hljs-string">"Double array contains:"</span>);
        printArray(doubleArr);   <span class="hljs-comment">// pass a Double array</span>

        System.out.println(<span class="hljs-string">"Character array contains:"</span>);
        printArray(charArr);   <span class="hljs-comment">// pass a Character array</span>
    }
</code></pre>
<p>We can call this generic method by passing different types of arrays (<code>Integer</code>, <code>Double</code>, <code>Character</code>) and you will see that your program will print the elements of each of these arrays.</p>
<p>##Restrictions on Generics</p>
<p>In Generics, we use bounds to restrict the types that a generic class, interface, or method can accept. There are two types:</p>
<p>####1. Upper Bounds
This is used to restrict the generic type to an upper limit. To define an upper bound, you use the <code>extends</code> keyword. By specifying an upper bound, you ensure that the class, interface, or method accepts the specified type and all of its subclasses.</p>
<p>The syntax would be as follows: <code>&lt;T extends SuperClass&gt;</code>.</p>
<p>If you consider the same <code>Box</code> class that we used previously, it can be modified as below:</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span>&lt;<span class="hljs-title">T</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Number</span>&gt; </span>{
    <span class="hljs-keyword">private</span> T value;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setValue</span><span class="hljs-params">(T value)</span> </span>{
        <span class="hljs-keyword">this</span>.value = value;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> T <span class="hljs-title">getValue</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> value;
    }
}
</code></pre>
<p>In this example, T can be any type that extends <code>Number</code>, such as <code>Integer</code>, <code>Double</code>, or <code>Float</code>.</p>
<p>####2. Lower Bounds
This is used to restrict the generic type to a lower limit. To define a lower bound, you use the <code>super</code> keyword. By specifying a lower bound, you ensure that the class, interface, or method accepts the specified type and all of its superclasses.</p>
<p>The syntax would be as follows: <code>&lt;T super SubClass&gt;</code>.</p>
<p>To illustrate the use of lower bounds, let us take a look at the following example:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">printList</span><span class="hljs-params">(List&lt;? <span class="hljs-keyword">super</span> Integer&gt; list)</span> </span>{
    <span class="hljs-keyword">for</span> (Object element : list) {
        System.out.print(element + <span class="hljs-string">" "</span>);
    }
    System.out.println();
}
</code></pre>
<p>The usage of a lower bound <code>&lt;? super Integer&gt;</code> ensures that you can pass the specified type and all of its superclasses, which in this case would be a list of <code>Integer</code>, <code>Number</code>, or <code>Object</code> to the method <code>printList</code>.</p>
<p>##What are Wildcards?</p>
<p>The <code>?</code> that you saw in the previous example is called a Wildcard. You can use them to refer to an unknown type. </p>
<p>You can use a wildcard with an upper bound, in which case it would look something like this: <code>&lt;? extends Number&gt;</code>. It can also be used with a lower bound, such as <code>&lt;? super Integer&gt;</code>.</p>
<p>##Type Erasure </p>
<p>The generic type that we use in our class, interface, or method is only available at compile time and it is removed at run-time. This is done to ensure backward compatibility, as the older versions of Java (before Java 1.5) do not support it.</p>
<p>The compiler makes use of the generic type information that is available to it to ensure type safety. In the process of type erasure:</p>
<ul>
<li>If the type is unbounded, then the parameters get replaced with their bounds or <code>Object</code> type</li>
<li>If the type is bounded, then the parameters get replaced by the first bound, and the generic type information will be removed after compilation</li>
</ul>
<p>If we take a look at the <code>Box</code> class example:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span>&lt;<span class="hljs-title">T</span>&gt; </span>{
    <span class="hljs-keyword">private</span> T value;
    <span class="hljs-comment">//getters and setters</span>
 }
</code></pre>
<p>The above code will become this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Box</span> </span>{
    <span class="hljs-keyword">private</span> Object value;
    <span class="hljs-comment">//getters and setters</span>
 }
</code></pre>
<p>##Conclusion</p>
<p>In this article, we explored the concept of generics in Java and how you can use them, with some basic examples. Understanding and using generics enhances type safety in your program. They also eliminate the need for explicit casting and make your code reusable and maintainable.</p>
<p>Let's connect on <a target="_blank" href="https://www.linkedin.com/in/abaradwaj/">LinkedIn</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use TypeScript Generics with Functional React Components ]]>
                </title>
                <description>
                    <![CDATA[ By Olasunkanmi Balogun In this article, we will explore the powerful synergy between TypeScript generics and functional React components.  Generics allow you to define flexible components that can adapt to different data structures and enforce type s... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/typescript-generics-with-functional-react-components/</link>
                <guid isPermaLink="false">66d46092d14641365a050947</guid>
                
                    <category>
                        <![CDATA[ generics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 27 Jul 2023 18:53:32 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/federico-beccari-ahi73ZN5P0Y-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Olasunkanmi Balogun</p>
<p>In this article, we will explore the powerful synergy between TypeScript generics and functional React components. </p>
<p>Generics allow you to define flexible components that can adapt to different data structures and enforce type safety throughout your codebase. </p>
<p>By leveraging Generics in functional components, you can create highly reusable and adaptable UI elements that can seamlessly handle varying data requirements.</p>
<p>In this tutorial, we'll begin by understanding the concept of generics in TypeScript and how they can be beneficial in the context of React development. </p>
<p>We will then dive into practical examples, demonstrating how to define generic functional components in React using TypeScript. </p>
<p>We'll also discuss various use cases where generic props shine, enabling us to build versatile and scalable React applications.</p>
<h2 id="heading-what-are-generics-in-typescript">What are Generics in TypeScript?</h2>
<p>In order to explore functional components with generics, you need to grasp the fundamentals of generic functions in TypeScript – including their definition and implementation. </p>
<p>In this section, you'll get a concise overview of what generics are and how to implement them in TypeScript. This should equip you with the necessary knowledge to delve deeper into the realm of functional components.</p>
<h3 id="heading-how-to-declare-a-generic-function-in-typescript">How to declare a generic function in TypeScript</h3>
<p>To declare a generic function in TypeScript, we place a generic type parameter, denoted as <code>&lt;T&gt;</code>, at the beginning of the function signature. This <code>&lt;T&gt;</code> represents a type that will be passed when the function is used. It serves as a placeholder for a specific type that will be determined during runtime, similar to how parameters behave in regular functions. </p>
<p>For instance, consider the following function:</p>
<pre><code class="lang-ts"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">value: T</span>):<span class="hljs-title">T</span>[] </span>{
   <span class="hljs-keyword">return</span> [value];
}

func(<span class="hljs-string">'Hello John'</span>);
</code></pre>
<p>In this example, the generic type parameter <code>T</code> is used to denote that the value parameter and the return type will be of the same type. </p>
<p>When the <code>func</code> function is called with the argument <code>'Hello John'</code>, the inferred type for <code>T</code> becomes <code>string</code>. As a result, the return type of the function is <code>string[]</code>, indicating that an array containing the provided string value will be returned.</p>
<h3 id="heading-how-to-define-generics-with-arrow-functions-in-typescript">How to define generics with arrow functions in TypeScript</h3>
<p>The syntax for defining a generic function with arrow functions is slightly different from that of the function declaration we've seen before:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> func = &lt;T&gt;(value: T):T[] =&gt; {
   <span class="hljs-keyword">return</span> [value];
}

func(<span class="hljs-string">'Hello John'</span>);
</code></pre>
<p>From the above, we see that when using arrow functions to define generic functions in TypeScript, we employ the <code>&lt;T&gt;</code> syntax before the parameter list to indicate a generic type parameter.</p>
<p>Moving on, it's important to note that the generic type parameter <code>T</code> used in the previous examples is merely a descriptive name and can be replaced with any other valid identifier. For example:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> func = &lt;K&gt;(value: K):K[] =&gt; {
   <span class="hljs-keyword">return</span> [value];
}

func(<span class="hljs-string">'Hello John'</span>);
</code></pre>
<p>The generic type parameter <code>T</code> has been replaced with <code>K</code>, showcasing that the choice of name for the generic type is flexible and can be customized to match the context or developer preference. </p>
<p>The function <code>func</code> remains generic, capable of accepting any type specified during usage and returning an array of that same type.</p>
<p>Now that you know how to implement generic functions and understand their flexibility in returning any passed type, we'll now learn how to implement generic components in React. </p>
<p>In the following section, I'll provide a step-by-step walkthrough of how to create and utilize generic components. This will help you harness the power of generics in React development.</p>
<h2 id="heading-how-to-define-and-use-generic-components-in-react">How to Define and Use Generic Components in React</h2>
<p>Just like with generic functions, you can take component reusability to the next level by designing generic components with the integration of TypeScript generics. </p>
<p>Declaring the generic props that a generic component will accept is the initial step in designing the component. We can build a parameterized props interface that supports different data types by using TypeScript generics.</p>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> MyComponentProps&lt;T&gt; {
  data: T;
  <span class="hljs-comment">// Add additional props specific to your component</span>
}
</code></pre>
<p>Once the generic props interface is defined, you can then implement the generic component itself. This involves using the declared generic props and integrating them into the component's structure. </p>
<p>Similar to the TypeScript function description in the previous section, it has the same implementation.</p>
<pre><code class="lang-tsx">function MyComponent&lt;T&gt;({ data }: MyComponentProps&lt;T&gt;) {

  return (
    &lt;div&gt;
      {/* JSX content */}
    &lt;/div&gt;
  );
}
</code></pre>
<p>Following this, you can also define generic components using arrow function syntax. But this is different when you are writing your code in a <code>JSX.Element</code> file.</p>
<p>To avoid ambiguity between generic type parameters and a <code>jsx</code> component, you add a trailing comma to the type parameter to differentiate it from a <code>JSX.Element</code>. For example:</p>
<pre><code class="lang-tsx">interface MyComponentProps&lt;T&gt; {
  data: T;
}
// notice the trailing comma after &lt;T
const MyComponent = &lt;T,&gt;({ data }: MyComponentProps&lt;T&gt;) =&gt; {
  return (
  &lt;div&gt;{JSX content}&lt;/div&gt;;
  )
};
export default MyComponent;
</code></pre>
<h3 id="heading-example-use-case-of-generic-components">Example Use Case Of Generic Components</h3>
<p>Let's say you want to develop a data visualization dashboard capable of presenting data from diverse sources, each with its unique structures and properties. But you want to create a reusable component that can generate a summary of any data object, focusing on a specific property.</p>
<p>This scenario provides an opportunity to delve into a practical application of a generic component in React. </p>
<p>By extending the type parameter to an <code>object</code> and utilizing the <code>keyof</code> operator within the interfaces, you can construct a component that offers both flexibility and type safety. </p>
<p>This approach harnesses the capabilities of TypeScript's robust type system, empowering you to work with a variety of objects seamlessly.</p>
<p>To achieve this, define a generic component called <code>Summary&lt;T&gt;</code> that accepts a type parameter <code>T</code> extending an object. You'll also use the <code>keyof</code> operator to specify the property of the object that you want to display in the summary:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> SummaryProps&lt;T <span class="hljs-keyword">extends</span> object, K <span class="hljs-keyword">extends</span> keyof T&gt; {
  data: T;
  property: K;
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Summary</span>&lt;<span class="hljs-title">T</span> <span class="hljs-title">extends</span> <span class="hljs-title">object</span>, <span class="hljs-title">K</span> <span class="hljs-title">extends</span> <span class="hljs-title">keyof</span> <span class="hljs-title">T</span>&gt;(<span class="hljs-params">{
  data,
  property,
}: SummaryProps&lt;T, K&gt;</span>) </span>{
  <span class="hljs-keyword">const</span> value = data[property] <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>;

  <span class="hljs-keyword">return</span> (
    &lt;div&gt;
      {(<span class="hljs-keyword">typeof</span> property === <span class="hljs-string">"string"</span>) ? (
        &lt;p&gt;
          {property}: {value}{<span class="hljs-string">" "</span>}
        &lt;/p&gt;
      ) : (
        <span class="hljs-string">""</span>
      )}
    &lt;/div&gt;
  );
}
</code></pre>
<p>In the <code>Summary</code> component, we defined a generic type parameter <code>T</code> that extends <code>object</code>, ensuring that data passed to the component is an <code>object</code> type. </p>
<p>The second type parameter <code>K</code> uses the <code>keyof</code> <code>T</code> notation, indicating that it must be a key of the <code>T</code> object type. This way, you can access a specific property of the data object based on the provided property value.</p>
<p>Within the component, we extracted the value from the data <code>object</code> using the <code>property</code> as the key. To ensure the value is treated as a <code>string</code>, we used the <code>as</code> keyword to perform a type assertion: <code>data[property] as string</code> to avoid assignment errors. This type assertion tells TypeScript to treat the value as a <code>string</code>.</p>
<p>The component then returns a <code>&lt;div&gt;</code> element containing a conditional rendering of a <code>&lt;p&gt;</code> element. The code then checks if the <code>property</code> is of type <code>string</code> using <code>typeof property === "string"</code>. In this way, it also prevents assignment mistakes.</p>
<p>If it evaluates to <code>true</code>, the code renders the <code>&lt;p&gt;</code> element, displaying the <code>property</code> and <code>value</code>. Otherwise, an empty <code>string</code> gets returned.</p>
<p>Having defined the component, let's consider an example where you have two different data sources: <code>User</code> and <code>Product</code>. Each data source has its own properties, but you want to display a summary based on a specific property.</p>
<p>You can start by defining the <code>User</code> interface to represent user data, specifying properties such as <code>id</code>, <code>name</code>, and <code>email</code>. Similarly, create the <code>Product</code> interface to represent product data, including properties like <code>id</code>, <code>name</code>, and <code>price</code>, like this:</p>
<pre><code class="lang-tsx">interface User {
  id: number;
  name: string;
  email: string;
}

interface Product {
  id: number;
  name: string;
  price: number;
}
</code></pre>
<p>Next, you can create instances of these data objects. For example, <code>userData</code> can represent a <code>user</code> and <code>productData</code> can represent a <code>product</code>, with their respective properties filled with sample data:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">const</span> userData: User = {
  id: <span class="hljs-number">1</span>,
  name: <span class="hljs-string">"John Doe"</span>,
  email: <span class="hljs-string">"johndoe@example.com"</span>
};

<span class="hljs-keyword">const</span> productData: Product = {
  id: <span class="hljs-number">1</span>,
  name: <span class="hljs-string">"Smartphone"</span>,
  price: <span class="hljs-number">999</span>
};
</code></pre>
<p>To utilize the <code>Summary</code> component, provide it with different data sources and specify the property you want to display in the summary. </p>
<p>For instance, you can use <code>&lt;Summary&lt;User, "name"&gt;&gt;</code> to render a summary of the user's name, and <code>&lt;Summary&lt;Product, "price"&gt;&gt;</code> to display the price of the product:</p>
<pre><code class="lang-ts">&lt;Summary&lt;User, <span class="hljs-string">"name"</span>&gt; data={userData} property=<span class="hljs-string">"name"</span> /&gt;
&lt;Summary&lt;Product, <span class="hljs-string">"price"</span>&gt; data={productData} property=<span class="hljs-string">"price"</span> /&gt;
</code></pre>
<p>The full code looks like this:</p>
<pre><code class="lang-ts"><span class="hljs-keyword">interface</span> User {
  id: <span class="hljs-built_in">number</span>;
  name: <span class="hljs-built_in">string</span>;
  email: <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">interface</span> Product {
  id: <span class="hljs-built_in">number</span>;
  name: <span class="hljs-built_in">string</span>;
  price: <span class="hljs-built_in">number</span>;
}

<span class="hljs-keyword">const</span> userData: User = {
  id: <span class="hljs-number">1</span>,
  name: <span class="hljs-string">"John Doe"</span>,
  email: <span class="hljs-string">"johndoe@example.com"</span>
};

<span class="hljs-keyword">const</span> productData: Product = {
  id: <span class="hljs-number">1</span>,
  name: <span class="hljs-string">"Smartphone"</span>,
  price: <span class="hljs-number">999</span>
};

<span class="hljs-comment">// Usage of Summary component with different data sources and properties</span>
&lt;Summary&lt;User, <span class="hljs-string">"name"</span>&gt; data={userData} property=<span class="hljs-string">"name"</span> /&gt;
&lt;Summary&lt;Product, <span class="hljs-string">"price"</span>&gt; data={productData} property=<span class="hljs-string">"price"</span> /&gt;
</code></pre>
<p>TypeScript's powerful type inference mechanism comes into play in this scenario. When you provide the <code>data</code> and <code>property</code> to the <code>Summary</code> component, TypeScript ensures that the specified property is valid for the corresponding data source. </p>
<p>If you mistakenly attempt to use an invalid property, such as providing <code>"email"</code> as the property for the <code>Product</code> data, the TypeScript compiler will raise a type error. This ensures type safety and helps prevent potential runtime issues.</p>
<p>By leveraging TypeScript's static type checking, we gain the benefits of type safety and validation when working with generic components like <code>Summary</code>. This also helps catch errors early in the development process and ensures that the provided <code>data</code> and <code>property</code> combinations are correct.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this guide, we have explored the concept of generics in TypeScript and how they can be applied to create powerful and reusable components in React. </p>
<p>Generics allow us to define components that are flexible enough to work with various data types while maintaining type safety.</p>
<p>Throughout this article, you learned generics fundamentals, including the implementation of generic functions. We then delved into the world of generic components in React, demonstrating how to define and implement them using both <code>arrow</code> and <code>named</code> function methods.</p>
<p>As you continue your journey with TypeScript, I encourage you to explore further the power and flexibility of generic props. By utilizing generics, you can unlock new possibilities in creating reusable and type-safe components that empower your React applications. Happy coding! </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ TypeScript Generics – Use Case and Examples ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, you'll learn the basics of generics in TypeScript. We'll discuss how to use them and when they're useful in your code. Use Case for Generics Let's start with a simple example, where  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/typescript-generics-use-case-and-examples/</link>
                <guid isPermaLink="false">66d45d9b052ad259f07e4a5d</guid>
                
                    <category>
                        <![CDATA[ generics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Aman Kalra ]]>
                </dc:creator>
                <pubDate>Fri, 07 Oct 2022 20:49:10 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/pexels-hitarth-jadhav-220357.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, you'll learn the basics of generics in TypeScript. We'll discuss how to use them and when they're useful in your code.</p>
<h2 id="heading-use-case-for-generics">Use Case for Generics</h2>
<p>Let's start with a simple example, where you want to print the value of an argument passed:</p>
<pre><code class="language-typescript">function printData(data: number) {
    console.log("data: ", data);
}

printData(2);
</code></pre>
<p>Now, let's suppose you want to make <code>printData</code> a more generic function, where you can pass any type of argument to it like: <strong>number</strong>/ <strong>string</strong>/ <strong>boolean</strong>. So, you might think to follow an approach like below:</p>
<pre><code class="language-typescript">function printData(data: number | string | boolean) {
    console.log("data: ", data);
}

printData(2);
printData("hello");
printData(true);
</code></pre>
<p>But in the future, you might want to print an array of numbers using the same function. In that case the types will increase and it will become cumbersome to maintain all those different types.</p>
<p>This is when <strong>Generics</strong> come into the picture.</p>
<h2 id="heading-how-generics-work-in-ts">How Generics Work in TS</h2>
<p>Generics are like variables – to be precise, type variables – that store the type (for example number, string, boolean) as a value.</p>
<p>So, you can solve the problem we discussed above with generics as shown below:</p>
<pre><code class="language-typescript">function printData&lt;T&gt;(data: T) {
    console.log("data: ", data);
}

printData(2);
printData("hello");
printData(true);
</code></pre>
<p>In the above example <code>printData-generics.ts</code>, there is a slight difference in syntax:</p>
<ol>
<li><p>You use a type variable inside angular brackets after the function name <code>&lt;T&gt;</code></p>
</li>
<li><p>You then assign the type variable to the parameter <code>data: T</code></p>
</li>
</ol>
<p>Let's explore these differences a bit more.</p>
<p>To use generics, you need to use angular brackets and then specify a type variable inside them. Developers generally use <code>T</code>, <code>X</code> and <code>Y</code>. But it can be anything depending upon your preference.</p>
<p>You can then assign the same variable name as the type to the parameter of the function.</p>
<p>Now, whatever argument you pass to the function, it gets inferred and there's no need to hardcode the type anywhere.</p>
<p>Even if you pass an array of numbers or an object to the <code>printData</code> function, everything will be displayed properly without TS complaining:</p>
<pre><code class="language-typescript">function printData&lt;T&gt;(data: T) {
    console.log("data: ", data);
}

printData(2);
printData("hello");
printData(true);
printData([1, 2, 3, 4, 5, 6]);
printData([1, 2, 3, "hi"]);
printData({ name: "Ram", rollNo: 1 });
</code></pre>
<p>Let's see another example:</p>
<pre><code class="language-typescript">function printData&lt;X,Y&gt;(data1: X, data2: Y) {
    console.log("Output is: ", data1, data2);
}

printData("Hello", "World");
printData(123, ["Hi", 123]);
</code></pre>
<p>In above example, we passed 2 arguments to <code>printData</code> and used <code>X</code> and <code>Y</code> to denote the types for both the parameters. <code>X</code> refers to 1st value of the argument and <code>Y</code> refers to 2nd value of the argument.</p>
<p>Here as well, the types of <code>data1</code> and <code>data2</code> are not specified explicitly because TypeScript handles the type inference with the help of generics.</p>
<h3 id="heading-how-to-use-generics-with-interfaces">How to Use Generics with Interfaces</h3>
<p>You can even use generics with interfaces. Let's see how that works with the help of a code snippet:</p>
<pre><code class="language-typescript">interface UserData&lt;X,Y&gt; {
    name: X;
    rollNo: Y;
}

const user: UserData&lt;string, number&gt; = {
    name: "Ram",
    rollNo: 1
}
</code></pre>
<p>In above snippet, <code>&lt;string, number&gt;</code> are passed to the interface <code>UserData</code>. In this way, <code>UserData</code> becomes a reusable interface in which any data type can be assigned depending upon the use case.</p>
<p>Here in this example, <code>name</code> and <code>rollNo</code> will always be <code>string</code> and <code>number</code>, respectively. But this example was to showcase how you can use generics with interfaces in TS.</p>
<h3 id="heading-thanks-for-reading">Thanks for reading!</h3>
<p>If you found this article useful, do share it with your friends and colleagues.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to generic types in Java: covariance and contravariance ]]>
                </title>
                <description>
                    <![CDATA[ By Fabian Terh Types Java is a statically typed language, which means you must first declare a variable and its type before using it. For example: int myInteger = 42; Enter generic types. Generic types Definition: “A generic type is a generic class o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/understanding-java-generic-types-covariance-and-contravariance-88f4c19763d2/</link>
                <guid isPermaLink="false">66c363eec6c49ae59cf21b33</guid>
                
                    <category>
                        <![CDATA[ generics ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 21 Sep 2018 04:00:37 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*h03xxe8xFKcFv262.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Fabian Terh</p>
<h3 id="heading-types">Types</h3>
<p>Java is a statically typed language, which means you must first declare a variable and its type before using it.</p>
<p>For example: <code>int myInteger = 42;</code></p>
<p>Enter generic types.</p>
<h4 id="heading-generic-types">Generic types</h4>
<p><a target="_blank" href="https://docs.oracle.com/javase/tutorial/java/generics/types.html">Definition</a>: “A <em>generic type</em> is a generic class or interface that is parameterized over types.”</p>
<p>Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.</p>
<p>Rather than specifying <code>obj</code> to be of an <code>int</code> type, or a <code>String</code> type, or any other type, you define the <code>Box</code> class to accept a type parameter <code>&lt;</code>;T&gt;. Then, you ca<code>n</code> use T to represent that generic type in any part within your class.</p>
<p>Now, enter covariance and contravariance.</p>
<h3 id="heading-covariance-and-contravariance">Covariance and contravariance</h3>
<h4 id="heading-definition">Definition</h4>
<p>Variance refers to how subtyping between more complex types relates to subtyping between their components (<a target="_blank" href="https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)">source</a>).</p>
<p>An easy-to-remember (and extremely informal) definition of covariance and contravariance is:</p>
<ul>
<li>Covariance: accept subtypes</li>
<li>Contravariance: accept supertypes</li>
</ul>
<h4 id="heading-arrays">Arrays</h4>
<p>In Java, <strong>arrays are covariant</strong>, which has 2 implications.</p>
<p>Firstly, an array of type <code>T[]</code> may contain elements of type <code>T</code> and its subtypes.</p>
<pre><code><span class="hljs-built_in">Number</span>[] nums = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Number</span>[<span class="hljs-number">5</span>];nums[<span class="hljs-number">0</span>] = <span class="hljs-keyword">new</span> Integer(<span class="hljs-number">1</span>); <span class="hljs-comment">// Oknums[1] = new Double(2.0); // Ok</span>
</code></pre><p>Secondly, an array of type <code>S[]</code> is a subtype of <code>T[]</code> if <code>S</code> is a subtype of <code>T</code>.</p>
<pre><code>Integer[] intArr = <span class="hljs-keyword">new</span> Integer[<span class="hljs-number">5</span>];<span class="hljs-built_in">Number</span>[] numArr = intArr; <span class="hljs-comment">// Ok</span>
</code></pre><p>However, it’s important to remember that: (1) <code>numArr</code> is a reference of reference type <code>Number[]</code> to the “actual object” <code>intArr</code> of “actual type” <code>Integer[]</code>.</p>
<p>Therefore, the following line will compile just fine, but will produce a runtime <code>ArrayStoreException</code> (because of heap pollution):</p>
<pre><code>numArr[<span class="hljs-number">0</span>] = <span class="hljs-number">1.23</span>; <span class="hljs-comment">// Not ok</span>
</code></pre><p>It produces a runtime exception, because Java knows at runtime that the “actual object” <code>intArr</code> is actually an array of <code>Integer</code>.</p>
<h4 id="heading-generics">Generics</h4>
<p>With generic types, Java has no way of knowing at runtime the type information of the type parameters, due to type erasure. Therefore, it cannot protect against heap pollution at runtime.</p>
<p><strong>As such, generics are invariant.</strong></p>
<pre><code>ArrayList&lt;Integer&gt; intArrList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();ArrayList&lt;<span class="hljs-built_in">Number</span>&gt; numArrList = intArrList; <span class="hljs-comment">// Not okArrayList&lt;Integer&gt; anotherIntArrList = intArrList; // Ok</span>
</code></pre><p>The type parameters must match exactly, to protect against heap pollution.</p>
<p>But enter wildcards.</p>
<h4 id="heading-wildcards-covariance-and-contravariance">Wildcards, covariance, and contravariance</h4>
<p>With wildcards, it’s possible for generics to support covariance and contravariance.</p>
<p>Tweaking the previous example, we get this, which works!</p>
<pre><code>ArrayList&lt;Integer&gt; intArrList = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();ArrayList&lt;? <span class="hljs-built_in">super</span> Integer&gt; numArrList = intArrList; <span class="hljs-comment">// Ok</span>
</code></pre><p>The question mark “?” refers to a wildcard which represents an unknown type. It can be lower-bounded, which restricts the unknown type to be a specific type or its supertype.</p>
<p>Therefore, in line 2, <code>? super Integer</code> translates to “any type that is an Integer type or its supertype”.</p>
<p>You could also upper-bound the wildcard, which restricts the unknown type to be a specific type or its subtype, by using <code>? extends Integer</code>.</p>
<h4 id="heading-read-only-and-write-only">Read-only and write-only</h4>
<p>Covariance and contravariance produce some interesting outcomes. <strong>Covariant types are read-only, while contravariant types are write-only.</strong></p>
<p>Remember that covariant types accept subtypes, so <code>ArrayList&lt;? extends Numb</code>er&gt; can contain any object that is either <code>of a</code> Number type or its subtype.</p>
<p>In this example, line 9 works, because we can be certain that whatever we get from the ArrayList can be upcasted to a <code>Number</code> type (because if it extends <code>Number</code>, by definition, it <em>is a</em> <code>Number</code>).</p>
<p>But <code>nums.add()</code> doesn’t work, because we cannot be sure of the “actual type” of the object. All we know is that it must be a <code>Number</code> or its subtypes (e.g. Integer, Double, Long, etc.).</p>
<p>With contravariance, the converse is true.</p>
<p>Line 9 works, because we can be certain that whatever the “actual type” of the object is, it must be <code>Integer</code> or its supertype, and thus accept an <code>Integer</code> object.</p>
<p>But line 10 doesn’t work, because we cannot be sure that we will get an <code>Integer</code>. For instance, <code>nums</code> could be referencing an ArrayList of <code>Objects</code>.</p>
<h4 id="heading-applications">Applications</h4>
<p>Therefore, since covariant types are read-only and contravariant types are write-only (loosely speaking), we can derive the following rule of thumb: <strong>“Producer extends, consumer super”</strong>.</p>
<p>A producer-like object that produces objects of type <code>T</code> can be of type parameter <code>&lt;? extends</code> T&gt;, while a consumer-like object that consumes objects of type T can be of type para<code>meter &lt;?</code> super T&gt;.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
