<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Charles on Medium]]></title>
        <description><![CDATA[Stories by Charles on Medium]]></description>
        <link>https://medium.com/@cizu64?source=rss-f764c7bc46ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-CnPvOhsCTDgDtOEyiyoyw.jpeg</url>
            <title>Stories by Charles on Medium</title>
            <link>https://medium.com/@cizu64?source=rss-f764c7bc46ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:18:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cizu64/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[How to Structure a Modular Monolith in .NET]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@cizu64/how-to-structure-a-modular-monolith-in-net-052ad23f107e?source=rss-f764c7bc46ee------2"><img src="https://cdn-images-1.medium.com/max/1746/1*03Jsw3d_wjkVUJ60GJ5D0Q.png" width="1746"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://medium.com/@cizu64/how-to-structure-a-modular-monolith-in-net-052ad23f107e?source=rss-f764c7bc46ee------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@cizu64/how-to-structure-a-modular-monolith-in-net-052ad23f107e?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/052ad23f107e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Wed, 27 May 2026 16:51:49 GMT</pubDate>
            <atom:updated>2026-05-27T16:51:49.341Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Hybrid RabbitMQ Publish Pattern with the Outbox Pattern]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@cizu64/hybrid-rabbitmq-publish-pattern-with-the-outbox-pattern-126cd55bb20c?source=rss-f764c7bc46ee------2"><img src="https://cdn-images-1.medium.com/max/1400/0*3sn_XLumbse4r-0r.png" width="1400"></a></p><p class="medium-feed-snippet">The Hybrid Publish Pattern</p><p class="medium-feed-link"><a href="https://medium.com/@cizu64/hybrid-rabbitmq-publish-pattern-with-the-outbox-pattern-126cd55bb20c?source=rss-f764c7bc46ee------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@cizu64/hybrid-rabbitmq-publish-pattern-with-the-outbox-pattern-126cd55bb20c?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/126cd55bb20c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 15:27:47 GMT</pubDate>
            <atom:updated>2025-12-30T15:29:25.618Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How To Structure Your Clean Architecture Project In ASP.NET Core]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@cizu64/how-to-structure-your-clean-architecture-project-in-asp-net-core-8557c4322e89?source=rss-f764c7bc46ee------2"><img src="https://cdn-images-1.medium.com/max/619/1*sBTLokViBU4mcQc_YVspfQ.png" width="619"></a></p><p class="medium-feed-snippet">That adrenaline rush when a great project idea pops into your head&#x200A;&#x2014;&#x200A;especially as a developer&#x200A;&#x2014;&#x200A;is unmatched. But the real challenge&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@cizu64/how-to-structure-your-clean-architecture-project-in-asp-net-core-8557c4322e89?source=rss-f764c7bc46ee------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@cizu64/how-to-structure-your-clean-architecture-project-in-asp-net-core-8557c4322e89?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/8557c4322e89</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 15:10:41 GMT</pubDate>
            <atom:updated>2025-09-13T15:10:41.159Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[What’s new in C# 14]]></title>
            <link>https://medium.com/@cizu64/whats-new-in-c-14-61fcba0bd384?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/61fcba0bd384</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Wed, 06 Aug 2025 12:35:29 GMT</pubDate>
            <atom:updated>2025-08-06T12:35:29.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*DOCT3N1WB2VDWs4v.jpg" /></figure><h3>Extension members</h3><p>Starting with <strong>C# 14</strong>, you can declare <strong>extension members</strong> using <strong>extension containers</strong> inside top-level, non-generic static classes. These extension members — methods or properties — can behave like instance or static members.</p><p>In earlier C# versions, extension methods were defined by marking the first parameter of a static method with the this modifier inside a static class.</p><p>With the new extension block syntax, you explicitly specify groups of related extension members. Inside the block, you can define both methods and properties. The example below shows an extension block containing one instance method and one instance property.</p><pre>using System.Linq;<br>public static class NewExtension<br>{<br>    extension(params int[] nums)<br>    {<br>        public int SumAll() =&gt; nums.Sum();<br><br>        public bool IsEven<br>        {<br>          get {return nums % 2 == 0;}<br>        }<br><br>    }<br>}</pre><pre>int[] nums = [1,2,3,4,5];<br>nums.SumAll();<br>bool isEven = nums.IsEven;</pre><p>The new extension block can also take a generic return type.</p><p>When declaring extension members using the extension block, where you place type parameters depends on <strong>how and where they are used</strong>:</p><ol><li><strong>Use type parameters in the </strong><strong>extension declaration: </strong>If the type parameter appears in the <strong>receiver</strong>, declare it at the extension block level.</li></ol><pre>using System.Linq;<br>public static class NewGenericExtension<br>{<br>    extension&lt;T&gt;(IEnumerable&lt;T&gt; entity) //entity is the reciver<br>    {<br>        public IEnumerable&lt;T&gt; Where (Func&lt;T, bool&gt; predicate) =&gt; entity.Where(p);<br>    }<br>}</pre><p>2. <strong>Use type parameters in the member declaration: </strong>If the type parameter is <strong>not used in the receiver</strong>, but only within a specific method or property, declare it at the <strong>member level</strong> instead.</p><pre>extension(IEnumerable&lt;object&gt; source)<br>{<br>    public List&lt;T&gt; ToTypedList&lt;T&gt;() =&gt; source.OfType&lt;T&gt;().ToList();<br>}</pre><blockquote><strong>Note</strong>: You cannot declare the <strong>same type parameter</strong> in both the extension block and the method. Doing so will result in a compiler error.</blockquote><h3>The Field Keyword</h3><p>The field keyword allows you to write property accessors without explicitly declaring a backing field. The compiler automatically generates the backing field and replaces field with it behind the scenes.</p><p>For example, to prevent a string property from being set to null, you previously had to declare a backing field manually and implement both the get and set accessors:</p><pre>public string Fullname<br>{<br>    get;<br>    set =&gt; field = value ?? throw new ArgumentNullException(nameof(value));<br>}</pre><p>Before C# 14</p><pre>private string _fullname; //backing field<br>public string Fullname<br>{<br>    get =&gt; _fullname;<br>    set =&gt; _fullname = value ?? throw new ArgumentNullException(nameof(value));<br>}</pre><blockquote>Note: The field keyword can be conflicting if it is a user defined variable. In cases like this you can use the @field keyword</blockquote><h3>Lambda Parameters</h3><p>All input parameters in a method must either have explicit types or be entirely implicit (using var-style inference);</p><p>Before C# 14, if a parameter used a modifier like ref or out, you were required to specify its type explicitly.</p><pre>Func&lt;int, int, bool&gt; isEven = (int a, int b) =&gt; a % b == 0;</pre><p>In C# 14, this restriction is removed — you dont need to specify the type</p><pre>Func&lt;int, int, bool&gt; isEven = (a, b) =&gt; a % b == 0;</pre><blockquote>Note: The params modifier <strong>still requires an explicit type</strong>, even in C# 14.</blockquote><h3>Unbound generic types and nameof</h3><p>Starting in C# 14, you can use nameof with unbound generic types. For example:</p><pre>nameof(List&lt;&gt;); // evaluates to &quot;List&quot;</pre><p>In earlier versions of C#, nameof only accepted <strong>closed generic types</strong>—types where the type parameters are fully specified. So you&#39;d need to write:</p><pre>nameof(List&lt;int&gt;); // evaluates to &quot;List&quot;</pre><h3>Conclusion</h3><p>Thank you for reading through. Don’t forget to enrol for my courses on Udemy. To gain deeper understanding of how Domain Driven Design operates, consider exploring an easily comprehensible <a href="https://www.udemy.com/course/domain-driven-design-in-net-core/?referralCode=5316BA92BB1321CBEF72">Udemy course</a> that explains everything from the basics with the source code included. This course also includes Software Design Patterns and Microservices.</p><p>Once you feel comfortable with DDD, Other architecture will prove beneficial and come in handy.</p><p>Additionally, if you’re interested in learning a robust frontend framework, take a look at an all-in-one course covering <a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5">Typescript, React, and NextJs</a>.</p><p>Cheers!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61fcba0bd384" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Gateways with Ocelot in .NET]]></title>
            <link>https://medium.com/@cizu64/api-gateways-with-ocelot-in-net-b9fd88729bb8?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9fd88729bb8</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Fri, 11 Apr 2025 21:53:13 GMT</pubDate>
            <atom:updated>2025-07-05T10:46:36.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>API Gateway in .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BwGEaDeyCweXo0k1Ytk9wg.png" /></figure><h3>Introduction</h3><p>API gateways act as intermediaries that intercept incoming requests and route them to the appropriate destination. They also play a crucial role in authorization, allowing authentication checks to be performed before a request reaches the downstream service.</p><p>In microservices architectures, API gateways are essential due to the independent nature of services. Additionally, they enhance security by concealing backend URLs, preventing direct exposure to clients.</p><h4>Ocelot API Gateway</h4><p>In ASP.NET, the <strong>ocelot</strong> NuGet package is used to create API Gateways.</p><p>Ocelot is an Open Source .NET Core based API Gateway especially useful for microservices architecture that need unified points of entry into their system. It’s lightweight, fast, scalable and provides routing and authentication among many other features.</p><blockquote>The API Gateway should be a standalone ASP.NET core application with a responsibility of just routing requests.</blockquote><p>The Ocelot gateway accepts requests as configured in the <strong>ocelot.json</strong> file and forwards it to its downstream service.</p><h4>Concepts</h4><p>The Ocelot API Gateway utilizes various terms, all of which can be defined within a single ocelot.json file, including:</p><ul><li><strong>GlobalConfiguration</strong>: The global configuration object mostly contains the BaseUrl that defines the base url of the api gateway.</li></ul><pre> &quot;GlobalConfiguration&quot;: {<br>    &quot;BaseUrl&quot;: &quot;http://localhost:5000/&quot;<br>  }</pre><ul><li><strong>Routes</strong>: The <strong>Routes</strong> are the objects that tell Ocelot how to treat an upstream request.</li><li><strong>Upstream</strong>: Upstream requests are url paths that can be accessible by clients can call and can also take {parameters} as query string or routes in the url. For eg</li></ul><pre> &quot;UpstreamPathTemplate&quot;: &quot;/api/soccer/fixtures{params}&quot;</pre><blockquote>{params} can take more as routes such as “<strong>/api/soccer/fixtures/1/2</strong>” as the request comes in.</blockquote><ul><li><strong>UpstreamHttpMethod</strong>: These are http verbs supported by the upstream url. It can be GET, POST, PUT, PATCH, DELETE, HEAD</li><li><strong>Downstream</strong>: This property defines the destination url the upstream request routes to</li><li><strong>DownstreamScheme: </strong>The scheme of the downstream url path can be http(s)</li><li><strong>DownstreamHostAndPorts</strong>: Defines the host and the port</li></ul><p>To know more about the configuration, check out the ocelot documentation at <a href="https://ocelot.readthedocs.io/en/latest/features/configuration.html">https://ocelot.readthedocs.io/en/latest/features/configuration.html</a></p><h4>Creating the Ocelot Project</h4><p>Create a new ASP.NET Core web API application and install the ocelot package</p><pre>dotnet add package Ocelot --version 23.4.3</pre><p>In the <strong>Program.cs</strong> class, we need to add the ocelot to the service collection and the middleware. The ocelot.json file is where the configuration for the API gateway resides, and can be configured to read configuration from another file or based on the environment.</p><pre>builder.Configuration.AddJsonFile(&quot;ocelot.json&quot;, false, true);<br>builder.Services.AddOcelot(builder.Configuration)<br>    .AddDelegatingHandler&lt;ApiKeyHandler&gt;();<br><br>var app = builder.Build();<br>await app.UseOcelot();</pre><h4>API Gateway configuration with Authentication</h4><p>In the ocelot.json file, the first scenario defines a route configuration with authentication that requires a bearer jwt token in the Authorization header.</p><pre>{<br>  &quot;GlobalConfiguration&quot;: {<br>    &quot;BaseUrl&quot;: &quot;http://localhost:5001&quot;<br>  },<br>  &quot;Routes&quot;: [<br>    {<br>      &quot;UpstreamPathTemplate&quot;: &quot;/api/soccer/fixtures{params}&quot;,<br>      &quot;UpstreamHttpMethod&quot;: [<br>        &quot;POST&quot;<br>      ],<br>      &quot;DownstreamPathTemplate&quot;: &quot;/api/soccer/fixtures{params}&quot;,<br>      &quot;DownstreamScheme&quot;: &quot;http&quot;,<br>      &quot;DownstreamHostAndPorts&quot;: [<br>        {<br>          &quot;Host&quot;: &quot;localhost&quot;,<br>          &quot;Port&quot;: &quot;5002&quot;<br>        }<br>      ],<br>      &quot;AuthenticationOptions&quot;: {<br>        &quot;AuthenticationProviderKey&quot;: &quot;Bearer&quot;<br>      }<br>    }<br>  ]<br>}</pre><blockquote>With this configuration in place, any POST request that comes to the upstream url (<strong><em>http://localhost:5001/api/soccer/fixtures/1/2) </em></strong>would be forwarded to the downstream url and it also requires bearer authorization.</blockquote><h3>Claims Transformation</h3><p>Once a user is <strong>authenticated</strong>, ocelot can transform claims in to headers, query string and even change downstream path. The several ways to add claims transformation are:</p><ul><li><strong>AddQueriesToRequest</strong></li><li><strong>ChangeDownstreamPathTemplate</strong>.</li></ul><p>These should be added in Route object in the ocelot.json file. Let’s look at the <strong>AddQueriesToRequest</strong> and <strong>ChangeDownstreamPathTemplate.</strong> Check out this <a href="https://ocelot.readthedocs.io/en/latest/features/claimstransformation.html">link</a> to know more about the several claims transformations available.</p><h4><strong>AddQueriesToRequest</strong></h4><p>Ocelot can transform the claims and add it to the query string parameters that gets forward to the <strong>downstream</strong></p><pre>{<br>  &quot;GlobalConfiguration&quot;: {<br>    &quot;BaseUrl&quot;: &quot;http://localhost:5001&quot;<br>  },<br>  &quot;Routes&quot;: [<br>    {<br>      &quot;UpstreamPathTemplate&quot;: &quot;/api/soccer/fixtures{params}&quot;,<br>      &quot;UpstreamHttpMethod&quot;: [<br>        &quot;POST&quot;<br>      ],<br>      &quot;DownstreamPathTemplate&quot;: &quot;/api/soccer/fixtures{params}&quot;,<br>      &quot;DownstreamScheme&quot;: &quot;http&quot;,<br>      &quot;DownstreamHostAndPorts&quot;: [<br>        {<br>          &quot;Host&quot;: &quot;localhost&quot;,<br>          &quot;Port&quot;: &quot;5002&quot;<br>        }<br>      ],<br>      &quot;AuthenticationOptions&quot;: {<br>        &quot;AuthenticationProviderKey&quot;: &quot;Bearer&quot;<br>      },<br>      &quot;AddQueriesToRequest&quot;: {<br>          &quot;Type&quot;: &quot;Claims[Type] &gt; value&quot;,<br>      }<br>    }<br>  ]<br>}</pre><p>The code above will look for the Claims[Type] after the user has authorized and it in the query string of the downstream url. So the downstream url should look like this “http://localhost:5001/api/soccer/fixtures?<strong>Type=”live”</strong></p><h4><strong>ChangeDownstreamPathTemplate</strong></h4><p>Ocelot can also transform claims based on a placeholder in the “DownstreamPathTemplate”.</p><pre>{<br>  &quot;GlobalConfiguration&quot;: {<br>    &quot;BaseUrl&quot;: &quot;http://localhost:5001&quot;<br>  },<br>  &quot;Routes&quot;: [<br>    {<br>      &quot;UpstreamPathTemplate&quot;: &quot;/api/soccer/fixtures&quot;,<br>      &quot;UpstreamHttpMethod&quot;: [<br>        &quot;POST&quot;<br>      ],<br>      &quot;DownstreamPathTemplate&quot;: &quot;/{mode}/api/soccer/fixtures&quot;,<br>      &quot;DownstreamScheme&quot;: &quot;http&quot;,<br>      &quot;DownstreamHostAndPorts&quot;: [<br>        {<br>          &quot;Host&quot;: &quot;localhost&quot;,<br>          &quot;Port&quot;: &quot;5002&quot;<br>        }<br>      ],<br>      &quot;AuthenticationOptions&quot;: {<br>        &quot;AuthenticationProviderKey&quot;: &quot;Bearer&quot;<br>      },<br>      &quot;ChangeDownstreamPathTemplate&quot;: {<br>          &quot;Type&quot;: &quot;Claims[mode] &gt; value&quot;,<br>      }<br>    },<br>    {<br>      &quot;UpstreamPathTemplate&quot;: &quot;/live/api/soccer/fixtures&quot;,<br>      &quot;UpstreamHttpMethod&quot;: [<br>        &quot;POST&quot;,<br>        &quot;GET&quot;,<br>        &quot;PUT&quot;,<br>        &quot;DELETE&quot;,<br>        &quot;PATCH&quot;<br>      ],<br>      &quot;DownstreamPathTemplate&quot;: &quot;/api/soccer/fixtures&quot;,<br>      &quot;DownstreamScheme&quot;: &quot;http&quot;,<br>      &quot;DownstreamHostAndPorts&quot;: [<br>        {<br>          &quot;Host&quot;: &quot;localhost&quot;,<br>          &quot;Port&quot;: &quot;5002&quot;<br>        }<br>      ]<br>    },<br>  ]<br>}</pre><p>The code above transforms the downstream url based on the <strong>Claims[mode]</strong> claims after authentication. The <strong>Claims[mode] </strong>is substituted with the placeholder in the DownstreamPathTemplate in the {mode} url.</p><p>Note, the key specified in the <strong>ChangeDownstreamPathTemplate</strong> must be the same than the placeholder specified in the <strong>DownstreamPathTemplate</strong>.</p><p>The example above also shows another object in the ocelot.json file that defines an upstream url based on the ChangeDownstreamPathTemplate transformation that was done. If the Claims[mode] is <strong>live, </strong>then it should route to<strong> </strong>“/api/soccer/<strong>live</strong>/fixtures” upstream url. The <strong>ChangeDownstreamPathTemplate </strong>is a preferred header transformation if you want to redirect users to different url based on some claims</p><blockquote>Also note that if the Claims[key] does not exists, the transformation would fail.</blockquote><h3>Handlers</h3><p>In <strong>Ocelot</strong>, <strong>Delegating Handlers</strong> are powerful tools that allow you to inject custom logic into the request/response pipeline <strong>before</strong> the request is forwarded to the downstream service.</p><p>They are similar to middlewares in .NET.</p><pre>public class ApiKeyHandler : DelegatingHandler<br>{<br>    protected override Task&lt;HttpResponseMessage&gt; SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)<br>    {<br>        var uri = request.RequestUri?.ToString();<br>        request.Headers.Add(&quot;key&quot;, &quot;value&quot;);<br>        return base.SendAsync(request, cancellationToken);<br>    }<br>}</pre><h4>Register the Handler</h4><p>The next step is to register the handler in the program.cs class. The AddDelegatingHandler also takes default global parameter that is set to false. If it is true, the handler is applied globally and if it is false, it is added to a specific route.</p><pre>builder.Services.AddOcelot(builder.Configuration)<br>    .AddDelegatingHandler&lt;ApiKeyHandler&gt;(); //the handler gets registered</pre><p>After registering the handler, it should be configured in the ocelot.json file.</p><pre>{<br>  &quot;GlobalConfiguration&quot;: {<br>    &quot;BaseUrl&quot;: &quot;http://localhost:5001&quot;<br>  },<br>  &quot;Routes&quot;: [<br>    {<br>      &quot;UpstreamPathTemplate&quot;: &quot;/api/soccer/fixtures{params}&quot;,<br>      &quot;UpstreamHttpMethod&quot;: [<br>        &quot;POST&quot;<br>      ],<br>      &quot;DownstreamPathTemplate&quot;: &quot;/api/soccer/fixtures{params}&quot;,<br>      &quot;DownstreamScheme&quot;: &quot;http&quot;,<br>      &quot;DownstreamHostAndPorts&quot;: [<br>        {<br>          &quot;Host&quot;: &quot;localhost&quot;,<br>          &quot;Port&quot;: &quot;5002&quot;<br>        }<br>      ],<br>      &quot;AuthenticationOptions&quot;: {<br>        &quot;AuthenticationProviderKey&quot;: &quot;Bearer&quot;<br>      },<br>     &quot;DelegatingHandlers&quot;: [<br>        &quot;ApiKeyHandler&quot;<br>      ]<br>    }<br>  ]<br>}</pre><h3>Conclusion</h3><p><strong>I hope you found this article helpful!</strong> To dive deeper, be sure to explore the official Ocelot <a href="https://ocelot.readthedocs.io/en/latest/index.html">documentation</a> for more advanced features and best practices. And if you’re looking for a structured learning path, don’t miss out on my full course on <a href="https://www.udemy.com/user/charles-3471/">Udemy</a> — designed to take your skills to the next level!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9fd88729bb8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Service Lifetimes in .NET (KeyedServices Included)]]></title>
            <link>https://medium.com/@cizu64/understanding-service-lifetimes-in-net-keyedservices-included-94fb0e355079?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/94fb0e355079</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 17:29:52 GMT</pubDate>
            <atom:updated>2025-03-27T16:16:44.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Service Lifetimes in .NET (KeyedServices Included)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9Xe3BV7G7i6HZk24DyB_Q.png" /></figure><p>ASP.NET Core provides service lifetimes that can be used to perform Dependency Injection in code.</p><p>Following the “D” in the SOLID principle that states that “High level class should not depend on low level class. They should depend on Abstractions”. ASP.NET Core makes heavy use of dependency injection through constructors and also provides several service lifetimes — Scoped, Transient and Singletons</p><p>The goal of the service lifetimes is to inject different services in our application and determine how this services are created and re-used.</p><p>There are four service lifetimes in .NET Core which are:</p><h4>Singleton Service Lifetime</h4><p>This lifetime ensures that object are created once and using throughout the pipeline. So no matter how many time you call this object, the value are always the same once instantiated until host restarts. The Singleton lifetime is best suited stateless object such as “Log” operations.</p><blockquote>They are like Global variables</blockquote><p>Let’s take a class called ClientId for example that just return a Guid.</p><pre><br>public class ClientId<br>{<br>    public Guid Id;<br>    public ClientId()<br>    {<br>        Id = Guid.NewGuid();<br>    }<br><br>    public Guid ShowGuid()<br>    {<br>        return Id;<br>    }<br>}</pre><p>This class assigns a Guid in the constructor and defines a method that show the value of the Guid. In the ServiceCollection, this class is injected as a singleton service life time</p><pre>services.AddSingleton&lt;ClientId&gt;();</pre><pre>using Microsoft.AspNetCore.Mvc;<br><br>namespace Lifetime.Controller;<br><br>[ApiController]<br>[Route(&quot;api/&quot;)]<br>public class LifetimeController : ControllerBase<br>{<br>    ClientId clientId;<br>    public LifetimeController(ClientId clientId)<br>    {<br>        this.clientId = clientId;<br>    }<br>    [HttpGet(&quot;lifetime&quot;)]<br>    public IActionResult Get()<br>    {<br>        return Ok(clientId.ShowGuid());<br>    }<br><br>}</pre><p>No matter how many times the Singleton() endpoint is called, it would always return the same Guid until host restarts.</p><h4>Scoped Service Lifetime</h4><p>The Scoped Service Lifetime are create once per request and used throughout the request pipeline.</p><blockquote>If the instance is resolved multiple times in the constructor, the same instance will be used throughout a single request.</blockquote><p>Using the previous code, if we change the service lifetime in the ServiceCollection to use a Scoped service, you will notice the value of the Guid always change. And in the controller, if we resolve the ClientId twice in the constructor and run the code, you will notice ClientId uses the same instance per request.</p><pre>services.AddScoped&lt;ClientId&gt;();</pre><pre>using Microsoft.AspNetCore.Mvc;<br><br>namespace Lifetime.Controller;<br><br>[ApiController]<br>[Route(&quot;api/&quot;)]<br>public class LifetimeController : ControllerBase<br>{<br>    ClientId clientId;<br>    ClientId clientId2;<br>    public LifetimeController(ClientId clientId, ClientId clientId2)<br>    {<br>        this.clientId = clientId;<br>        this.clientId2 = clientId2;      <br>    }<br>    [HttpGet(&quot;lifetime&quot;)]<br>    public IActionResult Get()<br>    {<br>        return Ok(new{id1 = clientId.ShowGuid(), id2=clientId2.ShowGuid()});<br>    }<br><br>}</pre><p>The best place to use a scope service is in Entity Framework where we can instantiate the DbContext and GenericRepositories once and used throughout the request. We don’t want to be creating a new instance this each time they are requested.</p><pre>service.AddDbContext&lt;BelemaContext&gt;(options =&gt;<br>   {<br>      options.UseNpgsql(configuration[&quot;ConnectionString&quot;], opt =&gt;<br>      {<br>          opt.EnableRetryOnFailure(15, TimeSpan.FromSeconds(30), errorCodesToAdd: null);<br>      });<br>   });</pre><blockquote>scoped by default</blockquote><h4>Transient Service LifeTime</h4><p>The Transient Service Lifetime are created each time they are requested. If we try the above code and change the service lifetime in the service collection to be a Transient service, you will notice that the value are not the same because they are created each time they are requested. They are best used for lightweight and stateless services.</p><pre>services.AddTransient&lt;ClientId&gt;();</pre><pre>using Microsoft.AspNetCore.Mvc;<br><br>namespace Lifetime.Controller;<br><br>[ApiController]<br>[Route(&quot;api/&quot;)]<br>public class LifetimeController : ControllerBase<br>{<br>    ClientId clientId;<br>    ClientId clientId2;<br>    public LifetimeController(ClientId clientId, ClientId clientId2)<br>    {<br>        this.clientId = clientId;<br>        this.clientId2 = clientId2;      <br>    }<br>    [HttpGet(&quot;lifetime&quot;)]<br>    public IActionResult Get()<br>    {<br>        return Ok(new{id1 = clientId.ShowGuid(), id2=clientId2.ShowGuid()});<br>    }<br><br>}</pre><h4>Keyed Services</h4><p>ASP.NET Core 8 introduces a new service lifetime called KeyedServices. KeyServices provides a mechanism to work with various service lifetime by giving them keys. There are 3 keys services namely:</p><ul><li>AddKeyedScoped</li><li>AddKeyedSingleton</li><li>AddKeyedTransient</li></ul><p>Here is how it works:</p><pre>services.AddKeyedSingleton&lt;ClientId&gt;(&quot;key1&quot;); //key1 is the key</pre><pre>using Microsoft.AspNetCore.Mvc;<br><br>namespace Lifetime.Controller;<br><br>[ApiController]<br>[Route(&quot;api/&quot;)]<br>public class LifetimeController : ControllerBase<br>{<br>   <br>    [HttpGet(&quot;lifetime&quot;)]<br>    public IActionResult Get([FromKeyedServices(&quot;key1&quot;)] ClientId client)<br>    {<br>        return Ok(clientId.ShowGuid());<br>    }<br><br>}</pre><p>To further your ASP.NET Core skills enrol for this course on <a href="https://bit.ly/3SAkXm8">Udemy</a> that explains everything from the basics with the source code included.</p><p>Also checkout my article on <a href="https://medium.com/@cizu64/how-to-structure-your-domain-driven-design-project-in-asp-net-core-dbec0cc0ce53">how to structure a domain driven design project</a> from ground up.</p><p>Additionally, if you’re interested in learning a robust frontend framework, take a look at an all-in-one course covering <a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5">Typescript, React, and NextJs</a>. This course also includes a backend developed in .NET to further enhance your software development skills.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94fb0e355079" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key Concepts of a Domain Driven Design Application in .NET Core]]></title>
            <link>https://medium.com/@cizu64/key-concepts-of-a-domain-driven-design-application-in-net-core-999820551f4b?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/999820551f4b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Tue, 20 Aug 2024 12:08:00 GMT</pubDate>
            <atom:updated>2024-08-20T12:09:59.580Z</atom:updated>
            <content:encoded><![CDATA[<h3>Key Concepts of a Domain Driven Design Application in .NET Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*92-uOrRdYNxDsXSPFninOg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJYnOEMpnEwZO6rvBi2J6A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZTAmRNFXGiFQDYpFICRPw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-p-wkD77nGbR0o32ifmIg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BEW9Q0lFZo2ftRQauzrRzw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZyOvtrRLus8Zvt9Buy6MA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUe-2MPSRGZdBX0WaY15WA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilN2GwZd6jUI0MIy3KqHNQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgs4fq55Hre1_hsOHgDEiA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2n81ULYtdxHoMjTP-Y2Fg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajOGKhH1XhGRKac9vvK8-Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHYxoBfIYqruVLNID22-uA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQmCd0qpyCOeIU9F-hMtEg.jpeg" /></figure><p>Also checkout how to structure the DDD project <a href="https://medium.com/@cizu64/how-to-structure-your-domain-driven-design-project-in-asp-net-core-dbec0cc0ce53">https://medium.com/@cizu64/how-to-structure-your-domain-driven-design-project-in-asp-net-core-dbec0cc0ce53</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=999820551f4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Strategy Design Pattern in C#]]></title>
            <link>https://medium.com/@cizu64/the-strategy-design-pattern-in-c-3ba863c47271?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ba863c47271</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-principles]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 18:01:53 GMT</pubDate>
            <atom:updated>2024-06-07T18:01:53.784Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will discuss <strong>Design Patterns</strong> and the strategy design pattern in C#.</p><h3>What are Design patterns?</h3><p><a href="https://www.youtube.com/@techwithcharles"><strong>Design Patterns</strong></a> are reusable solutions to commonly occurring problems in software design.</p><p>If you’re a software engineer and haven’t yet explored software design patterns, now’s the perfect time to catch up!</p><p>There is a pattern for anything you want to achieve. You may have used one yourself without even knowing it, but it is a good idea to know about it because it makes your code mature, robust, testable, and reusable.</p><p>The software design pattern was introduced by four authors known as the <strong>Gang of Four</strong>, who published a book titled “Elements of Reusable Object-Oriented Software” which became so popular.</p><p>There are 23 design patterns that solve different problems. You don’t have to know all the design patterns, but it is better to get familiar with the famous ones and gradually introduce others as you practice them and apply them to your code. Design patterns also work hand in hand with the <a href="https://medium.com/@cizu64/solid-principles-in-c-fdc883435ff1"><strong>SOLID</strong></a><strong> </strong>principles. Knowing the <a href="https://medium.com/@cizu64/solid-principles-in-c-fdc883435ff1"><strong>SOLID</strong></a><strong> </strong>principles and Design patterns would make you a better software engineer but it is not mandatory to know the SOLID principles in order to work with <a href="https://www.youtube.com/@techwithcharles"><strong>Design Patterns</strong></a></p><h3>What is a Strategy Design Pattern</h3><p>A strategy is a <strong>behavioural design pattern</strong> that allows you to define a family of algorithms and interchange their objects at runtime.</p><p>These algorithms are dispersed in various classes and communicate via a common interface. The client decides the implementation of the object to be used at runtime.</p><p>For example, you are creating an app that allows people to register their basic profile in order to gain access to use the application features. This was done successfully, but in the future, there was a new requirement to incorporate users work profiles.</p><p>To do this the developer would need to modify the existing code that already supports the basic profile creation to also suit the work profile requirements. By doing this, the class responsible for creating the basic profile would have to be modified which can break existing client and the class also need to be retested because of the new work profile requirements.</p><p>A solution to this problem is to create a separate class and define the algorithm (business logic) for the work profile creation. Therefore, the already existing class may not be modified and does not need to be retested because noting was changed.</p><p>This can be achieved by using a <strong>Strategy pattern</strong>.</p><p>To begin, a strategy interface is defined, from which all concrete strategies implement and extract their behaviours, as well as a context class, which has a reference to the concrete strategy and communicates only through the strategy interface.</p><p>You may have probably use the Strategy Pattern without even knowing it.</p><p>The context class is responsible for delegating work to a strategy via its interface defined in the constructor parameters.</p><p>The Strategy pattern improves your code by:</p><ul><li>Writing less conditional statements</li><li>It supports the <a href="https://medium.com/@cizu64/solid-principles-in-c-fdc883435ff1">OCP</a> principle by allowing you to create new strategies without modifying the existing strategies</li><li>It makes your code manageable and testable.</li></ul><h3>Structure of a Strategy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-1o7uHnn2dSiJr3aO41jGQ.png" /></figure><p>To implement the Strategy pattern, we need to define:</p><ol><li>The Strategy Interface defines algorithms common to all concrete classes.</li><li>The client decides the strategy to pass to the context</li><li>The concrete strategies implement the various algorithms of the Strategy interface that the context class uses</li><li>The context class is what the client uses to call the desired strategy at runtime. This class is responsible for delegating work to a strategy via its interface defined in the constructor parameters.</li></ol><h3>Building the User Profile Management App</h3><p>Let’s create the profile management app we discussed about using the Strategy Design Pattern.</p><h4>Step 1: Defining the Strategy Interface</h4><pre> interface IProfile<br>  {<br>      object AddProfile(object data);<br>      object GetProfile();<br>  }</pre><h4>Step 2: Defining Concrete Classes that Implements the Strategy Interface</h4><pre>class BasicProfile : IProfile<br>{<br>    List&lt;object&gt; items = null;<br>    object IProfile.AddProfile(object data)<br>    {<br>        items = new List&lt;object&gt;<br>        {<br>            data<br>        };<br>        return items;<br>    }<br><br>    object IProfile.GetProfile()<br>    {<br>        return items ?? new List&lt;object&gt;();<br>    }<br>}</pre><p>The BasicProfile class implements the interface method AddProfile and GetPtofile. These methods are just responsible for adding a list of user profile object to a List and returning the objects from the list</p><pre> class JobProfile : IProfile<br>    {<br>        List&lt;object&gt; items = null;<br>        object IProfile.AddProfile(object data)<br>        {<br>            items = new List&lt;object&gt;<br>            {<br>                data<br>            };<br>            return items;<br>        }<br><br>        object IProfile.GetProfile()<br>        {<br>            return items ?? new List&lt;object&gt;();<br>        }<br>    }</pre><p>Now let’s create the context class that the client uses to call the desired strategy at runtime.</p><h4>Step 3: The Context Class</h4><pre> //the context class that has a reference to the concrete strategy and communicate only via the stategy interface<br>  class UserProfile<br>  {<br>      IProfile profile;<br>      public UserProfile(IProfile profile)<br>      {<br>          this.profile = profile;<br>      }<br>    <br>      public void AddProfile(object data)<br>      {<br>          Console.WriteLine($&quot;Adding {Type.GetType(profile.ToString()).Name}&quot;);<br>           this.profile.AddProfile(data);<br>         <br>      }<br>      public void GetProfile()<br>      {<br>          var result = this.profile.GetProfile();<br>          var json = JsonConvert.SerializeObject(result);<br>          Console.WriteLine(json);<br>      }<br>  }</pre><p>The Context class defines a reference to the strategy interface in its constructor and it also defines method to add and get profile through the interface method.</p><h4>Step 4: Running it</h4><pre>UserProfile profile = new UserProfile(new BasicProfile());<br>profile.AddProfile(new<br>{<br>    Id = 1,<br>    UserId = 1,<br>    Fullname = &quot;John Doe&quot;,<br>    Email = &quot;johndoe@gmail.com&quot;,<br>    Phone = &quot;12345&quot;,<br>    Gender = &quot;Male&quot;<br>});<br>profile.GetProfile();<br><br>profile = new UserProfile(new JobProfile()); //let&#39;s work with job profile<br>profile.AddProfile(new<br>{<br>    UserId = 1,<br>    ExpectedSalary = 70000,<br>    CV = &quot;link to cv&quot;<br>});<br>profile.GetProfile();</pre><p>In the code snippet above, notice that the context class was instantiated and in its parameter, it wraps the BasicProfile class because that class implements the <strong>IProfile</strong> interface and the UserProfile context class references the <strong>IProfile</strong> Strategy Interface in its constructor.</p><p>So it is through the context class we can work with different variations of the strategies defined and not by instantiating the concrete strategy directly and instead of modifying existing strategies, we can create new concrete strategies that implements the strategy interface therefore adhering to the <a href="https://medium.com/@cizu64/solid-principles-in-c-fdc883435ff1"><strong>OCP</strong></a> principles and <a href="https://medium.com/@cizu64/solid-principles-in-c-fdc883435ff1"><strong>SRP</strong></a>.</p><h3>Conclusion</h3><p>I will be writing more about design patterns in C#, so don’t hesitate to follow me for more interesting topics.</p><p>Also Check out my article on SOLID principles in .NET or enrol for this <a href="https://www.udemy.com/course/domain-driven-design-in-net-core/?referralCode=5316BA92BB1321CBEF72">Udemy course</a> on Domain Driven Design in .NET Core that also introduces SOLID Principles and a modern architecture for building robust software in .NET Core.</p><p>Additionally, if you’re interested in learning a robust frontend framework, take a look at an all-in-one course covering <a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5">Typescript, React, and NextJs</a>. This course also includes a backend developed in .NET to further enhance your software development skills.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ba863c47271" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Web Application Performance with LoadingUI and Suspense in React and NextJs]]></title>
            <link>https://medium.com/@cizu64/improving-web-application-performance-with-loadingui-and-suspense-in-react-and-nextjs-46a816ea9d6d?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a816ea9d6d</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Tue, 28 May 2024 23:41:58 GMT</pubDate>
            <atom:updated>2024-05-28T23:41:58.830Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*lQw580S84oqKukM5.jpg" /></figure><h3>Quick Intro</h3><p><a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5"><strong>React and NextJs</strong></a> remains a robust framework for building rich user centric application In 2024. While various frameworks like Vue and Angular have been used to develop web applications, React has proven to be a game-changer and remains one of the best libraries for web application development.</p><p>React is a versatile library that can be used to build various types of applications. However, it is recommended to use a framework like Next.js, which is built on top of React and offers additional features for developing web applications.</p><p>If you’re not familiar with NextJS, You can refer to the <a href="https://nextjs.org/docs">documentation</a> or enrol in this comprehensive Udemy course covering <a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5">TypeScript, React, and NextJS</a> that equips you with all the knowledge and skills necessary to become versatile with React and Next.</p><p>So let’s get to the nitty-gritty of Loading UI and Suspense in NextJs which is an incredible feature that improves the performance of web applications</p><h3>Loading UI</h3><p>Loading UI, as the name suggests, refers to displaying a loading ui such as skeletons, gifs, or text — on a web page while the original content is still loading. Once the content is ready, the page is displayed, and the loading UI disappears. This approach enhances user experience by informing users that content is being loaded and they need to wait a few seconds to see it.</p><p><strong>Let’s experiment with this in VSCode</strong></p><h4><strong>Step 1</strong></h4><p>Open visual studio code and create a folder named “training” and ensure that folder is open is vscode. Ensure you also have <a href="https://nodejs.org/en/download/prebuilt-installer"><strong>NodeJs</strong></a> installed version 18.17 or later</p><h4><strong>Step 2</strong></h4><p>Run this command in the terminal to get the NextJs app bootstrapped and ensure you are on the training directory and just press enter when prompted.</p><pre>npx create-next-app@latest<br><br>Need to install the following packages:<br>create-next-app@14.2.3 ok to proceed? (y) y<br>What is your project named? … my-app<br>Would you like to use TypeScript? … No / Yes<br>Would you like to use ESLint? … No / Yes<br>Would you like to use Tailwind CSS? … No / Yes<br>Would you like to use &#39;src/&#39; directory? … No / Yes<br>Would you like to use App Router? (recommended) No / Yes<br>Would you like to customize the default import alias (@/*)? … No / Yes Creating a new Next.js app in /Users/charles/ReactApps/traning/my-app.</pre><h4>Step 3</h4><p>Run the NextJs application</p><pre>cd my-app<br>npm run dev</pre><blockquote>This will open the application on localhost port 3000 which can be accessible in the browser.</blockquote><h4>Step 4</h4><p>In the app folder, create a nested folder named “<strong>learning</strong>” and a <strong>page.tsx</strong> file inside the learning route. In NextJs routes are configured through folders in the app directory and route can have a default <strong>page.tsx</strong> file which is the index page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOY8uTsGfQ2uyC2ow_rXYQ.png" /><figcaption>folder structure</figcaption></figure><p>Navigate to the url <strong>localhost:3000/learning</strong> and the page will be displayed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CeRB6I_Cj6mcwHOB6CvTMg.png" /></figure><h4><strong>Step 5</strong></h4><p>Now let’s create the loading ui starting by creating a loading.tsx in the learning route folder. By convention when NextJs sees the loading.tsx file in the route, it automatically knows it is a loader and the content of that file will be displayed while the original content is loading. So in order to see this in action, let simulate a delay and show a loading ui</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*5RRlnefF-qjMkew1r2B_uw.png" /><figcaption>loading.tsx</figcaption></figure><blockquote>The <strong>loading.tsx</strong> file just displays a loading italic text</blockquote><p>Next, let’s simulate a delay for 5 seconds in the default <strong>learning/page.tsx</strong> so we can see loader in action</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*He4fSHDRXtQDsm2q_oPuUA.png" /></figure><p>Now, save and refresh the browser, you will see the loading ui content being renders within 5 seconds before the original content.</p><h4>Summary</h4><p>We’ve seen how to add a loading UI to the learning route. To enable the loading UI on every page within the application, move the<strong> loading.tsx</strong> file to the app route. This ensures that every page displays the loading UI before rendering the original content.</p><p>Interesting, right? Yes! However, one drawback of this approach is that it applies only to the entire page. If you need to show a loader only for a specific section, like a div displaying football match fixtures, this method is insufficient. This is where Suspense comes in to solve the problem.</p><h3>Suspense</h3><p>Suspense breaks down page into chunks by wrapping the content or part of the ui with suspense. By using this approach, parts of the page can be rendered while some keeps loading. Therefore, you dont have to wait for the entire page to load.</p><p>Let’s go through the steps to achieve this right away!</p><h4>Step 1</h4><p>Create a <strong>country.tsx</strong> component in the app route that will display the name of a country from a restful service. we are going to use fetch api to achieve this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*79btqSlF--io6yfNDg5Xqw.png" /></figure><h4><strong>Step 2</strong></h4><p>Create a folder named “learn” in the app route folder and a page.tsx inside the learn folder and import the country component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zjaaloW7N77RI9uiS0QTsQ.png" /></figure><p>When you navigate to the <strong>/learn</strong> url , you should see the country name “Germany” displayed in the browser.</p><p>The goal we are trying to achieve is to wrap the Country component in a suspense so a loader is shown while the original content is fetched from the server because this may be a time consuming operation and the other content that is beneath the Country component is just a static text.</p><h4>Step 3</h4><p>Now let’s wrap the Country component with a suspense by importing the suspense library from react</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nPxqlb-X417XpBEiMb_pRw.png" /></figure><p>Now when you refresh the page, you will notice the loading country… text is shown before while the original content is being fetched from the server. The benefit of using suspense is it can be called multiple time in the application in sections that are time consuming.</p><p>You can use a loading ui together with a suspense in a page. The loading ui is shown when the page is loading while the suspense is show when a section in the page is still loading before it becomes available thus improving the performance of the web application.</p><h3>Conclusion</h3><p>Loading ui and suspense is a crucial aspect we should not omit when building React applications because it improves the performance of the application and user experience.</p><p>For a better understanding, here is a Y<a href="https://www.youtube.com/watch?v=rG238YQAeK0">ouTube</a> video explaining loading UI and Suspense in detail.</p><p>If you are not familiar with NextJs or still a React newbie, enrol for this powerful Udemy course that covers both <a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5">Typescript, React and NextJs</a>. This course equips you with everything needed to become a React and NextJs guru.</p><p>Hope you enjoyed this article!</p><p>Best of luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a816ea9d6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The only article you need to read to become an Expert in TypeScript!]]></title>
            <link>https://medium.com/@cizu64/discover-the-ultimate-guide-to-mastering-typescript-essentials-1321f9e4e9d5?source=rss-f764c7bc46ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/1321f9e4e9d5</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Charles]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 14:09:22 GMT</pubDate>
            <atom:updated>2024-05-23T15:52:40.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*md2MTpzK0dVDmxs8.png" /><figcaption>typescript</figcaption></figure><p>TypeScript is an open-source high-level programming language from Microsoft that extends JavaScript by integrating static typing and optional type annotations.</p><p>It retains all the features of JavaScript while introducing a robust type system for dynamic type checking during development.</p><p>Developers can specify types for variables, function parameters, return values, and other elements, thereby improving tooling support and detecting errors at compile time rather than runtime.</p><p>If you have prior experience with JavaScript, TypeScript will prove useful. Typescript is utilized across various frontend frameworks such as <a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5">NextJs, React, and Vue</a>, all of which also offer support for JavaScript. Moreover, familiarity with object-oriented programming (OOP) principles will further enhance your utilization of TypeScript.</p><p>Let’s discuss about the key features of Typescript starting with the static-type checking:</p><ul><li><strong>Static-type checking</strong> checks your code for errors on the go. Static type systems define the structures and actions of our values before execution. A type-checker such as TypeScript utilizes this data to inform us when there is an error.</li><li>Another key feature of typescript is the tsc compiler that you can use to type check your code by running the tsc command in a terminal. Note, before you can use the tsc command, ensure that typescript is installed globally via npm.</li><li>TypeScript supports <strong>Enums</strong>, which allow developers to define a set of named constants. Typescript support both string and numeric based Enums</li><li>TypeScript also offers support for <strong>classes, interfaces, and custom types</strong>. Developers can define classes in an object-oriented programming (OOP) fashion, as well as create custom data structures and contracts. Interfaces serve as blueprints for objects, ensuring that objects adhere to a specified shape.</li><li>Typescript also supports <strong>static</strong> methods in classes and also <strong>Generics</strong> that allows for code reusability.</li></ul><h3>Basic Types</h3><p>Let’s delve into the fundamental types provided by TypeScript, which encompass various data types including <strong>strings</strong>, <strong>numbers</strong>, <strong>booleans</strong>, and the versatile “<strong>any</strong>” type, among others. Additionally, we’ll explore more advanced types and their applications within TypeScript.</p><p>The most commonly used types in typescript are <strong>string</strong>, <strong>boolean</strong> and <strong>number</strong>. Strings represent string values like “hello john” and number is for numbers either integers, floats, decimal are all classified as <strong>number</strong> type in typescript. And finally, <strong>boolean</strong> represents true or false.</p><p>Lets define these types right away in code , we are going to use the typescript playground to do this starting with the <strong>string</strong> type. Visit the Typescript playground <a href="https://www.typescriptlang.org/play">https://www.typescriptlang.org/play</a> and follow along.</p><h4>String type</h4><pre>/*javascript*/<br>//let message<br>//message = &quot;Welcome to typescript&quot;<br>//console.log(message)<br><br>/*typescript version*/<br>let message:string<br>message = &quot;Welcome to typescript&quot; //use a number and you get an error<br>console.log(message)</pre><blockquote>The code above shows how to define a string in javascript and typescript. The typescript version defines the type for the message variable and does static type checking.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*8oo8nNazFX72Ka3ALq8mQA.png" /><figcaption>type checking</figcaption></figure><blockquote>Typescript type checker will highlight the error if a number is assigned to the string message variable, therefore allow us to see the errors on the go and avoid pitfalls</blockquote><h4>Number type</h4><p>Decimals, floats and integers are all classified as <strong>number </strong>type in typescript.</p><pre>let age:number<br>age = 30 //must be a number<br>//age = 30.5 //also works<br>//age = 20 + 10 //also works<br>console.log(age)</pre><blockquote>the variable “age” must be a number because they type number is used.</blockquote><p>In javascript age can take any type such and number + string. If we use the javascript approach this is what we get:</p><pre>let age;<br>age = 10 + &quot;hello&quot;; //javascript will see this as a string<br>//age = 10 + &quot;hello&quot; + true; //javascript will also see this as a string<br>//age = 10 &gt; 10 //now a boolean<br>console.log(age)</pre><blockquote>when we run this code, we get “10 hello” as the result. Javascript is going to see the variable as a string because the age variable does not have a type, so it is going to accept any value.</blockquote><h4>Boolean type</h4><p>The boolean type is a conditional type that can be either true or false in typescript.</p><pre>let age:number = 30;<br>let mustBe18:boolean = age &gt; 18<br>console.log(mustBe18)</pre><h4>Array type</h4><p>Arrays in typescript are similar to arrays in javascript. But with typescript you can add type annotations that ensures type safety. Let’s start by defining an array in javascript</p><pre>/*arrays in javascript*/ <br>let numbers;<br>numbers = [1,2,3] //can accept any value<br>numbers = [1,2,3,&quot;hello&quot;,true]<br>console.log(numbers)<br>console.log(numbers[3])</pre><blockquote>JavaScript, being an untyped language, is prone to type safety bugs, occurring when an unintended type is mistakenly used instead of the expected one. This is the problem typescript solves.</blockquote><p>In typescript, you can define an array of string, booleans, number or even the any type array. Typescript also support generic array classes.</p><pre>let numbers = number[]<br>numbers = [1,2,3,4]<br>//numbers = [1,2,3,4,&quot;&quot;] //this will cause an error<br>console.log(numbers)</pre><pre>let word:string[] = [&quot;welcome&quot;,&quot;to&quot;]<br>word.push(&quot;typescript&quot;)<br>//word.push(1) //would cause an error<br>console.log(word)</pre><pre>let word:any[] = [&quot;welcome&quot;,&quot;to&quot;]<br>word.push(&quot;typescript&quot;,1,[3,4,5])<br>console.log(word[4][1]) //returns 4</pre><blockquote>The any type as the name implies support all types</blockquote><p>We can also use the generic <strong>Array&lt;&gt;</strong> class in typescript to define arrays.</p><pre>let numbers: Array&lt;number&gt;<br>numbers = [1,2,3,4]<br>//numbers = [1,2,3,4,&quot;&quot;] //this will cause an error<br>console.log(numbers)<br><br>let word:Array&lt;string&gt; = [&quot;welcome&quot;,&quot;to&quot;]<br>word.push(&quot;typescript&quot;)<br>//word.push(1) //would cause an error<br>console.log(word)<br><br>let words:Array&lt;any&gt; = [&quot;welcome&quot;,&quot;to&quot;]<br>words.push(&quot;typescript&quot;,1,[3,4,5])<br>console.log(words[4][1]) //returns 4</pre><p>In TypeScript, there is a special type known as “<strong>any</strong>.” It serves as a versatile placeholder, allowing you to bypass type checking when a specific value’s type is uncertain or irrelevant to your current needs. We have used this type in the example above.</p><p>In TypeScript, you have the ability to specify both parameter types and return types for functions. This means you can declare the types of input parameters as well as the type of the value returned by the function.</p><pre>function Sum(nums:Array&lt;number&gt;):number<br>{<br>   //The reduce() method reduces all elements in an array into a single value.<br>   let result:number =  nums.reduce((accumulator,currentValue)=&gt;<br>   {<br>       return accumulator + currentValue  <br>   })<br>   return result<br>}<br><br>console.log(Sum([1,2,3,4]))</pre><blockquote>the Sum function defines a type for the nums parameter and also the type of the function return type which is a number</blockquote><h4>Object type</h4><p>So far, we’ve been utilizing primitive types in the examples provided. Another frequently encountered type, particularly when dealing with JSON data, is the object type, representing any JavaScript value with properties.</p><pre>function DisplayProfile({name,age}:{name:string,age:number}):any<br>{<br>    return {name, age} <br>}<br><br>let profile = DisplayProfile({name:&quot;John&quot;, age:30});<br><br>console.log(`${profile.name} is ${profile.age} years old`);</pre><blockquote>The code above accept an object type as a parameter and each of those properties are assigned to their types.</blockquote><h4>Optional Properties</h4><p>In Typescript, you can designate optional properties by appending a question mark to the property name. This informs TypeScript that the property is not required. Simply add the question mark after the property name to achieve this.</p><pre>function DisplayProfile({name,age}:{name:string,age?:number}):any<br>{<br>    return {name, age} <br>}<br><br>let profile = DisplayProfile({name:&quot;John&quot;});<br><br>console.log(`${profile.name} is ${profile.age} years old`);</pre><blockquote>The age property is optional by appending the question mark after the property name. When we run this piece of code in the playground, we get “John is undefined years old”. To remove the undefined, we can specify the default value for age or use the double question “??” to define a value of the variable is undefined</blockquote><pre>function DisplayProfile({name,age}:{name:string,age?:number}):any<br>{<br>    return {name, age} <br>}<br><br>let profile = DisplayProfile({name:&quot;John&quot;});<br><br>console.log(`${profile.name} is ${profile.age??18} years old`);</pre><p>We can also do it this way:</p><pre>function DisplayProfile({name,age=18}:{name:string,age?:number}):any<br>{<br>    return {name, age} <br>}<br><br>let profile = DisplayProfile({name:&quot;John&quot;}); //no age<br><br>console.log(`${profile.name} is ${profile.age} years old`);</pre><blockquote>The age defaults to 18 when the age variable is not specified in the console.log message</blockquote><h4>Union types</h4><p>Another noteworthy feature in TypeScript is the Union types.Union types in TypeScript allow variables or parameters to have multiple possible types. They are denoted using the pipe operator between each type. Below is how to declare a Union type in the typescript playground.</p><pre>function DisplayProfile({name,age}:{name:string,age:number|string}):any<br>{<br>    return {name, age} <br>}<br><br>let profile = DisplayProfile({name:&quot;John&quot;, age:&quot;Thirty&quot;}); //age can be a number or string<br>console.log(`${profile.name} is ${profile.age} years old`);</pre><h4>Type aliases</h4><p>Type aliases in TypeScript allow us to create custom names for types, making our code more expressive and reusable. Instead of repeatedly defining complex types or combinations of existing types, we can create a single alias that represents them. This not only enhances code readability but also simplifies maintenance and reduces duplication. With type aliases, we can encapsulate intricate type definitions into easily understandable names, promoting code clarity and maintainability.</p><pre>type profile =<br>{<br>  name:string,<br>  age:number|string<br>}<br><br>function DisplayProfile({name,age}:profile):any<br>{<br>    return {name, age} <br>}<br><br>const AgeVerification = (profile:profile) =&gt;<br>{<br>    return profile.age as number &gt; 18<br>};<br><br>let profile = DisplayProfile({name:&quot;John&quot;, age:30});<br><br>console.log(`${profile.name} is ${profile.age} years old`);<br>console.log(`${profile.name} ${AgeVerification(profile) &amp;&amp; &#39;is liable&#39; || &#39;is not liable&#39;}`);</pre><blockquote>the profile type alias can be reused in different places thus avoiding the need to create duplicates.</blockquote><h4>Interfaces</h4><p>Another TypeScript feature resembling type aliases is interfaces. Interfaces provide a means to outline the structure of objects, serving as contracts that mandate the properties and methods an object should possess. They support extension, allowing for enhanced flexibility. While type aliases and interfaces share similarities, interfaces offer the added capability of extension, distinguishing them from type aliases while type aliases cannot be reopened to add new properties.</p><pre>interface IProfile<br>{<br>  name:string,<br>  age:number|string<br>}<br><br>function DisplayProfile({name,age}:IProfile):any<br>{<br>    return {name, age} <br>}<br><br>const AgeVerification = (profile:IProfile) =&gt;<br>{<br>    return profile.age as number &gt; 18<br>};<br><br>let profile = DisplayProfile({name:&quot;John&quot;, age:30});<br><br>console.log(`${profile.name} is ${profile.age} years old`);<br>console.log(`${profile.name} ${AgeVerification(profile) &amp;&amp; &#39;is liable&#39; || &#39;is not liable&#39;}`);</pre><pre>interface IProfile<br>{<br>  name:string,<br>  age:number|string<br>}<br><br>class Profile implements IProfile //implements the contract interface<br>{<br>    name: string;<br>    age: string|number;<br>    constructor(name:string,age:number)<br>    {<br>        this.name=name;<br>        this.age = age;<br>    }<br>}<br><br>const profile = new Profile(&quot;John&quot;,30);<br>console.log(`${profile.name} is ${profile.age} years old`);</pre><p>Another feature in TypeScript is type assertion, which is similar to casting in object-oriented programming languages like C#, achieved through the “as” keyword. There are instances where TypeScript may not accurately infer the type of a value, but as a developer, you possess that knowledge. By utilizing the “as” keyword, you can explicitly specify the actual type just as shown in the previous examples.</p><pre>const AgeVerification = (profile:IProfile) =&gt;<br>{<br>    return profile.age as number &gt; 18 //because age is a number and a string we need to do type assertion<br>};</pre><h3>TypeScript Classes</h3><p>If you are familiar with object oriented programming this section on classes should come in handy. Typescript supports the class keyword introduced in ES2015.</p><p>Classes in TypeScript provide a way to implement object-oriented programming (OOP) concepts such as encapsulation, inheritance, and polymorphism.</p><p>Let’s explore what you can do with classes in typescript starting with class definition with fields. Fields can be known as a public writable property on a class and they can have an optional type annotation <strong><em>with its default to any type if no type is assigned.</em></strong></p><p>The example below shows a class declaration with two assigned fields, one annotated with the number type and the other not annotated which would automatically use the “any” type.</p><pre>class Profile<br>{<br>    name: string;<br>    age; //defaults to any type<br>    constructor(name:string,age)<br>    {<br>        this.name=name;<br>        this.age = age;<br>    }<br>}<br><br>const profile = new Profile(&quot;John&quot;,&quot;30&quot;);<br>console.log(`${profile.name} is ${profile.age} years old`);</pre><h4>Readonly fields</h4><p>Fields can also have readonly modifiers just as with OOP programming languages such as C#, a readonly field can be assigned only through its constructor. The example below shows a class declaration with readonly fields that can only be assigned through its constructor. If you try to assign it outside its constructor, you get a typescript error.</p><pre>class Profile<br>{<br>    readonly name: string;<br>    age:number;<br>    constructor(name:string,age:number)<br>    {<br>        this.name = name;<br>        this.age = age;<br>    }<br>    tryToAssign = (name) =&gt; name; //wrong!!! can only assign name in the constructor<br>}<br><br>const profile = new Profile(&quot;John&quot;,30);<br>console.log(`${profile.name} is ${profile.age} years old`);</pre><h4>Constructors</h4><p>A notable feature of classes in TypeScript is constructors. Constructors are similar to constructors in object-oriented programming (OOP) languages, supporting overloading, parameters, and default parameter values. It’s worth noting that constructors lack return types, can have type parameters, and require the `super()` method to be called if the class extends another, granting access to the `this` keyword. To explore this further, experiment with the example provided on the TypeScript playground.</p><pre>class ProfessionalProfile<br>{<br>    linkedIn:string<br>    github:string<br>    constructor(linkedIn:string, github:string){<br>        this.linkedIn=linkedIn<br>        this.github=github<br>    }<br>}<br><br>class Profile extends ProfessionalProfile<br>{<br>    name: string;<br>    age:number;<br>    constructor(name:string,age:number)<br>    {<br>        super(&quot;linkedin.com&quot;,&quot;github.com&quot;); //super calls the base constructor<br>        this.name=name;<br>        this.age = age;<br>    }<br>}<br><br>const profile = new Profile(&quot;John&quot;,30);<br>console.log(`${profile.name} is ${profile.age} years old`);<br>console.log(`professional profile: linkedin: ${profile.linkedIn} github: ${profile.github}`)</pre><pre>class Profile<br>{<br>    name?: string;<br>    age?:number<br>    constructor()<br>    constructor(name?:string,age?:number)<br>    {<br>        this.name=name;<br>        this.age=age;<br>    }<br>}</pre><h4>Methods</h4><p>Methods are like functions in javascript that can contain parameters and can also have a return type. Up to this point, we’ve been illustrating methods in our examples, so this should come in handy.</p><pre>class Profile<br>{<br>    Method1()<br>    {<br>        console.log(&quot;in method one&quot;)<br>    }<br>    Method2 = () =&gt;<br>    {<br>       console.log(&quot;in method two&quot;)<br>    }<br>    Method3 = (name:string) =&gt;<br>    {<br>       console.log(name)<br>    }<br>}<br><br>new Profile().Method1()</pre><h4>Getters and Setters</h4><p>Classes in typescript can also have getters and setters accessors. Accessors resemble properties in OOP, so this should come in handy. Let’s define an accessor in the playground right away using the code below.</p><pre>class Profile {<br>  _fullname:string = &quot;&quot;; //can also have access visibility<br>  get fullname() {<br>    return this._fullname;<br>  }<br>  set fullname(value) {<br>    this._fullname = value;<br>  }<br>}<br><br><br>const profile = new Profile()<br>profile.fullname =&quot;John&quot;<br>console.log(profile.fullname)</pre><h4>Interfaces</h4><p>In TypeScript, you can adhere to an interface by implementing its signature in a concrete class. This class must fulfil the structure defined by the interface and can also introduce its own fields and methods. This is achieved through the “implements” clause. We have already seen this in action in previous examples, let define this further.</p><pre>interface IProfile {}<br><br>interface IRank {}<br><br>//an interface can also extend another interface<br>interface IScore extends IRank {}<br><br>class ProfessionalProfile {}<br><br>//implement the interface IProfile<br>class Profile implements IProfile {}<br><br>//can also extend a class and implement an interface<br>class Profile2 extends ProfessionalProfile implements IProfile {}<br><br>//can also implement multiple interfaces<br>class Profile3 implements IProfile, IRank {}</pre><h4>Access modifiers</h4><p>In object-oriented programming languages like C#, access modifiers regulate access to methods and declare properties or methods as either publicly accessible or restricted within a class. Similarly, in TypeScript, you can define member visibility to specify whether properties or methods are accessible beyond the scope of its class.</p><p>These member visibilities are — The public which is the default, the private and the protected member visibilities.</p><p>When you define a method without no visibility, then it defaults to the public member visibility.</p><p>A public member can be accessible anywhere. So far, in our examples we have not specified any member visibility. By default we have been working with public visibility because it is the default when you don’t specify.</p><p>However, when you want a class to have methods, properties or fields that can only be private to that class, use the private visibility. When a method is declared as private, even subclasses cannot access it.</p><p>However, if you want only a child or subclass to access its base class methods or fields but you don’t other classes to have access to it, you can use the protected member visibility.</p><pre><br>class ProfessionalProfile {}<br><br>class Profile <br>{<br>   private name:string;<br>   constructor(name:string)<br>   {<br>    this.name=name<br>   }<br><br>   private Display = () =&gt; console.log(this.name);<br>}<br><br>const profile = new Profile(&quot;John&quot;)<br>profile.name //cannot access profile.name because its has private member visibility<br>profile.Display() //cannot access profile.name because its has private member visibility</pre><pre><br>class ProfessionalProfile {<br>    protected linkedin?:string //only subclass can have access to this field<br>    get LinkedIn()<br>    {<br>        return this.linkedin<br>    }<br>    set LinkedIn(value) {<br>        this.linkedin = value;<br>    }<br>}<br><br>class Profile extends ProfessionalProfile <br>{<br>   private name:string;<br>   constructor(name:string)<br>   {<br>    super();<br>    this.name=name<br>   }<br><br>   private Display = () =&gt; console.log(this.name);<br>   DisplayProfessionalProfile = () =&gt; console.log(this.linkedin); //default to public member visibility<br>}<br><br>const profile = new Profile(&quot;John&quot;)<br>profile.LinkedIn = &quot;https://linkedin.com&quot;;<br>profile.DisplayProfessionalProfile();</pre><h4>Static members</h4><p>In TypeScript, classes can have static members, but the <strong>concept of static classes doesn’t exist</strong>. Unlike some object-oriented programming languages like C#, where a class can be designated as static, TypeScript doesn’t support static classes. Instead, you define static members within a class using the `static` keyword. These members belong to the class itself, allowing you to access them directly via the class name without needing to instantiate the class.</p><p>Static members can also have access modifiers which we discussed earlier such as <strong>public, private and protected</strong> and can also be inherited.</p><pre><br>class ProfessionalProfile {<br>    protected static linkedin?:string //only subclass can have access to this field<br>    static get LinkedIn()<br>    {<br>        return this.linkedin<br>    }<br>    static set LinkedIn(value) {<br>        this.linkedin = value;<br>    }<br>}<br><br>class Profile extends ProfessionalProfile <br>{<br>   private name:string;<br>   constructor(name:string)<br>   {<br>    super();<br>    this.name=name<br>   }<br><br>   private Display = () =&gt; console.log(this.name);<br>   static DisplayProfessionalProfile = () =&gt; console.log(this.linkedin); //default to public member visibility<br>}<br><br>Profile.LinkedIn = &quot;https://linkedin.com&quot;;<br>Profile.DisplayProfessionalProfile();</pre><h4>Generic classes</h4><p>Another amazing feature you can do with typescript are creating generic classes that ensures type safety and reusability. Generics does not only work with classes but also interfaces. To understand how generics works, let dive into the code:</p><pre>class Data&lt;T&gt;<br>{<br>    data:T;<br>    constructor(data:T)<br>    {<br>       this.data=data;<br>    }<br>    DisplayData()<br>    {<br>       console.log(&quot;type of data is: &quot; + typeof this.data);<br>    }<br>}<br>var data = new Data(1);<br>data.DisplayData()</pre><blockquote>The Data class can accept any type</blockquote><pre>interface IProfile&lt;T&gt;<br>{<br>   data:T;<br>}<br>class Data implements IProfile&lt;number&gt;<br>{<br>    data;<br>    constructor(data:number)<br>    {<br>          this.data=data;<br>    }<br>    DisplayData()<br>    {<br>         console.log(&quot;type of data is: &quot; + typeof this.data);<br>    }<br>}<br>var data = new Data(1);<br>data.DisplayData()</pre><h4>Abstract classes</h4><p>Typescript also allows you to define abstract classes just as you can do with other programming languages such as C#. An Abstract class is a class that cannot be instantiated and it serves as a base class for subclasses. Methods and fields can also be declared as abstract. Let see an example</p><pre>abstract class Base<br>{<br>    abstract SayHello():void;<br>}<br>class Derived extends Base<br>{<br>    SayHello() //this overrides the Base class SayHello() method<br>    {<br>       console.log(&quot;hello&quot;)<br>    }<br>}<br><br>new Derived().SayHello();</pre><h3>TypeScript Enums</h3><p>Enums in TypeScript offer a method for defining a collection of named constants, a feature absent in JavaScript.</p><p>There are various types of enums: Numeric Enums and String Enums, which are more popular. Additionally, there are Heterogeneous Enums, though their usage is infrequent.</p><p><strong>Numeric enums</strong> in TypeScript are automatically assigned a default value of “0”. However, if you specify a starting value, subsequent values will be incremented accordingly. For instance, if you assign “1” as the initial value, the next value will be “2”.</p><pre>enum Account<br>{<br>    SAVINGS = 1,<br>    CURRENT,<br>    FIXED<br>}<br>console.log(Account.SAVINGS)</pre><p><strong>String enums</strong> in TypeScript differ from numeric enums. With string enums, you must assign each member a string literal value.</p><pre>enum Account<br>{<br>    SAVINGS = &quot;Savings&quot;,<br>    CURRENT = &quot;Current&quot;,<br>    FIXED=&quot;Fixed&quot;<br>}<br>console.log(Account.SAVINGS)</pre><h3>TypeScript in HTML</h3><p>To use typescript in html just as we normally do in javascript by including the &lt;script&gt; tag and specifying the path to script in the src attribute, in typescript we need to compile it using this command:</p><pre>npm install -g typescript</pre><blockquote>Note: Node js needs to be installed before running npm</blockquote><p>After installing typescript globally, the we can run this command:</p><pre>tsc file1.ts</pre><blockquote>The tsc command is used to compile typescript to javascript and also used to check for errors. After compilation, it generate a file1.js javascript file that can be used in html files.</blockquote><h3>Conclusion</h3><p>Up to this point, we’ve explored the fundamental aspects of TypeScript which is a superset of javascript. TypeScript is gaining popularity due to its ability to perform all functionalities achievable with JavaScript, along with additional capabilities like Enums, which are not possible in JavaScript alone. Web frameworks such as Angular, React and Vue supports TypeScript due to its robust type checking features.</p><p>Enhance your TypeScript skills by enrolling in our course, “<a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5">Typescript, React and NextJs for Beginners</a>.” This comprehensive course provides you with the essential tools to elevate your proficiency as a web developer. React stands as one of the most prevalent frontend libraries, powering renowned web applications like Instagram, WhatsApp, Netflix, and many others. Moreover, Next.js serves as a robust framework for React. Don’t let this opportunity pass you by — <a href="https://www.udemy.com/course/all-in-one-beginners-guide-to-typescript-react-nextjs/?referralCode=6406EB1753D8CA7120A5">enroll now!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1321f9e4e9d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>