<?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 Dillirajtimalsina on Medium]]></title>
        <description><![CDATA[Stories by Dillirajtimalsina on Medium]]></description>
        <link>https://medium.com/@dillirajtimalsina354?source=rss-8801448700cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*F_CU53a9lI3XFFOq</url>
            <title>Stories by Dillirajtimalsina on Medium</title>
            <link>https://medium.com/@dillirajtimalsina354?source=rss-8801448700cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:52:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dillirajtimalsina354/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[SQL Joins and complexity analysis .]]></title>
            <link>https://medium.com/@dillirajtimalsina354/sql-joins-and-complexity-analysis-9010fe3d507d?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9010fe3d507d</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 02:36:36 GMT</pubDate>
            <atom:updated>2025-08-26T02:36:36.085Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Joins and complexity analysis .</h3><p>When working with relational databases like <strong>PostgreSQL</strong>, data is stored in multiple tables. To make sense of it, we need to <strong>combine rows</strong> from different tables. That’s where <strong>SQL Joins</strong> come in.</p><p>Most tutorials explain only the “what” of joins let’s go deeper into the “how” by also covering <strong>time and space complexity</strong>.</p><h3>Types of SQL Joins</h3><ol><li><strong>INNER JOIN</strong> → Matches rows from both tables.</li><li><strong>LEFT JOIN</strong> → Keeps all rows from the left table, adds NULL where no match on the right.</li><li><strong>RIGHT JOIN</strong> → Keeps all rows from the right table, adds NULL where no match on the left.</li><li><strong>FULL OUTER JOIN</strong> → Keeps all rows from both sides, NULL where no match.</li><li><strong>CROSS JOIN</strong> → Cartesian product (all combinations).</li><li><strong>SELF JOIN</strong> → A table joins with itself.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B576HsYS1kHdqGzxcY_atQ.png" /></figure><ol><li><strong>INNER JOIN :</strong></li></ol><pre>SELECT l.symbol, c.company_name<br>FROM listed_securities l<br>INNER JOIN company_info c<br>    ON l.symbol = c.symbol;</pre><p><strong>Complexity:</strong></p><ul><li>Time: <strong>O(N × M)</strong> worst case (if no indexes).</li><li>With index on symbol: <strong>O(N log M)</strong> (binary search on right table per row).</li><li>Space: <strong>O(min(N, M))</strong> to hold matched rows.</li></ul><p><strong>2. LEFT JOIN :</strong></p><pre>SELECT l.symbol, c.company_name<br>FROM listed_securities l<br>LEFT JOIN company_info c<br>    ON l.symbol = c.symbol;</pre><p><strong>Complexity:</strong></p><ul><li>Time: <strong>O(N × M)</strong> (worst case).</li><li>With index: <strong>O(N log M)</strong>.</li><li>Space: <strong>O(N)</strong> (must keep all rows from left table).</li></ul><p>3. <strong>RIGHT JOIN :</strong></p><pre>SELECT l.symbol, c.company_name<br>FROM listed_securities l<br>RIGHT JOIN company_info c<br>    ON l.symbol = c.symbol;</pre><p><strong>Complexity:</strong></p><ul><li>Time: Same as LEFT JOIN, but keeps all right rows.</li><li>Space: <strong>O(M)</strong> (to hold right table’s full set).</li></ul><p>4. <strong>FULL OUTER JOIN :</strong></p><pre>SELECT l.symbol, c.company_name<br>FROM listed_securities l<br>FULL OUTER JOIN company_info c<br>    ON l.symbol = c.symbol;</pre><p><strong>Complexity:</strong></p><ul><li>Time: <strong>O(N × M)</strong> worst case.</li><li>With indexes: <strong>O(N log M + M log N)</strong>.</li><li>Space: <strong>O(N + M)</strong>.</li></ul><p><strong>5. CROSS JOIN — not so important explore yourself .</strong></p><p><strong>6. SELF JOIN — not so important explore yourself .</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9010fe3d507d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Users, Roles, and Privileges in PostgreSQL]]></title>
            <link>https://medium.com/@dillirajtimalsina354/mastering-users-roles-and-privileges-in-postgresql-7e8939a958f9?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e8939a958f9</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 10:27:23 GMT</pubDate>
            <atom:updated>2025-08-18T10:27:23.776Z</atom:updated>
            <content:encoded><![CDATA[<p>PostgreSQL offers a powerful and flexible privilege system that allows administrators to control access to databases with precision. Understanding how to manage users, roles, and privileges is essential for ensuring both security and efficient database administration.</p><p>This guide explains the difference between users and roles, outlines the types of privileges available, and demonstrates how to grant, revoke, and manage access in PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKAned5fEKcVD3u0IJa9pQ.png" /></figure><h3>Users and Roles in PostgreSQL</h3><p>In PostgreSQL, access control is built on the concept of <strong>roles</strong>. Unlike other database systems that distinguish between users and groups, PostgreSQL uses roles for both purposes.</p><ul><li><strong>User</strong>: A role that has login capability. This represents an entity that can connect to the database.</li><li><strong>Role</strong>: A general construct that can be used either as a user (with login) or as a group (without login) to hold permissions.</li></ul><pre>-- Create a user with login capability<br>CREATE USER dilli WITH PASSWORD &#39;securepassword&#39;;<br><br>-- Create a role without login (acts as a permission group)<br>CREATE ROLE analysts;<br><br>-- Create a role with login<br>CREATE ROLE admin LOGIN PASSWORD &#39;adminpass&#39;;</pre><p>A user can be assigned one or more roles to inherit additional privileges.</p><h3>Role-Level Privileges</h3><p>Role-level privileges define what a role can do at the global level, independent of specific database objects .</p><ul><li><strong>LOGIN</strong>: Allows the role to connect to the database.</li></ul><pre>CREATE ROLE my_user LOGIN PASSWORD &#39;mypassword&#39;;</pre><p><strong>CREATEDB</strong>: Grants the ability to create new databases.</p><pre>GRANT CREATEDB TO developer_role;</pre><ul><li><strong>CREATEROLE</strong>: Allows creation and management of other roles.</li></ul><pre>GRANT CREATEROLE TO admin_role;</pre><ul><li><strong>SUPERUSER</strong>: Provides unrestricted access across the database system.</li></ul><pre>ALTER ROLE super_admin WITH SUPERUSER;</pre><ul><li><strong>REPLICATION</strong>: Grants replication-related privileges.</li></ul><pre>GRANT REPLICATION TO replication_role;</pre><ul><li><strong>BYPASSRLS</strong>: Allows bypassing of Row-Level Security policies.</li></ul><pre>GRANT BYPASSRLS TO admin_role;</pre><p>Privileges can be revoked in the same way:</p><pre>REVOKE CREATEROLE FROM admin_role;</pre><h3>Object-Level Privileges</h3><p>Object-level privileges determine what actions a role can perform on specific database objects such as tables, schemas, views, and functions.</p><p>Common privileges include:</p><ul><li><strong>SELECT</strong>: Query data from a table or view.</li><li><strong>INSERT</strong>: Add new rows to a table.</li><li><strong>UPDATE</strong>: Modify existing rows.</li><li><strong>DELETE</strong>: Remove rows.</li><li><strong>TRUNCATE</strong>: Remove all rows from a table quickly.</li><li><strong>REFERENCES</strong>: Create foreign keys referencing the table.</li><li><strong>TRIGGER</strong>: Create triggers on a table.</li><li><strong>USAGE</strong>: Use schemas, sequences, or domains.</li><li><strong>EXECUTE</strong>: Run stored functions or procedures.</li><li><strong>CREATE</strong>: Create new objects within a schema.</li><li><strong>ALL PRIVILEGES</strong>: Grants all privileges available for the object.</li></ul><h3>Examples</h3><pre>-- Grant SELECT and INSERT on a table<br>GRANT SELECT, INSERT ON TABLE customers TO john;<br><br>-- Revoke a privilege<br>REVOKE INSERT ON TABLE customers FROM john;<br><br>-- Grant schema usage<br>GRANT USAGE ON SCHEMA public TO john;</pre><h3>Role-Based Access Control in Practice</h3><p>PostgreSQL’s role-based access control (RBAC) makes managing permissions more scalable by grouping privileges into roles.</p><h3>Example 1: Limited Admin Role</h3><pre>CREATE ROLE admin_role;<br>GRANT CREATEROLE TO admin_role;<br>GRANT admin_role TO jane_doe;</pre><p>Here, jane_doe can create roles but does not have superuser privileges.</p><h3>Example 2: Read-Only Analyst Role</h3><pre>-- Step 1: Create a user<br>CREATE ROLE data_analyst WITH LOGIN PASSWORD &#39;StrongPassword&#39;;<br><br>-- Step 2: Allow connection to a database<br>GRANT CONNECT ON DATABASE my_database TO data_analyst;<br>-- Step 3: Grant schema access<br>GRANT USAGE ON SCHEMA public TO data_analyst;<br>-- Step 4: Allow SELECT on all current tables<br>GRANT SELECT ON ALL TABLES IN SCHEMA public TO data_analyst;<br>-- Step 5: Ensure access to future tables<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public<br>GRANT SELECT ON TABLES TO data_analyst;</pre><p>The analyst can now log in, query data, and access all current and future tables, but cannot modify data.</p><h3>Best Practices for Managing Privileges</h3><ol><li><strong>Apply Least Privilege</strong>: Assign only the privileges necessary for each role to minimize risk.</li><li><strong>Use Group Roles</strong>: Create roles that represent sets of permissions and assign them to users, instead of granting privileges individually.</li><li><strong>Restrict Superuser Access</strong>: Limit superuser privileges to trusted database administrators.</li><li><strong>Audit Regularly</strong>: Review roles and privileges periodically to ensure they align with responsibilities.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e8939a958f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Descriptive Statistics : Heart of Statistics . (Part 2 )]]></title>
            <link>https://medium.com/@dillirajtimalsina354/descriptive-statistics-heart-of-statistics-part-2-baa61000060c?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/baa61000060c</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machıne]]></category>
            <category><![CDATA[stats]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Mon, 26 May 2025 04:34:53 GMT</pubDate>
            <atom:updated>2025-05-26T04:37:40.109Z</atom:updated>
            <content:encoded><![CDATA[<h3>Descriptive Statistics : Heart of Statistics . (Part 2 )</h3><h3>What Is Descriptive Statistics?</h3><p>Descriptive statistics is a branch of statistics that <strong>summarizes and describes</strong> the features of a dataset. It doesn’t try to make predictions — it simply tells you what’s going on in your data right now.</p><p>It answers questions like:</p><ul><li>What’s the average value?</li><li>How spread out are the numbers?</li><li>Are there any outliers?</li><li>Is the data symmetric or skewed?</li></ul><p>Descriptive statistics can be broken into <strong>three main components</strong>:</p><ol><li><strong>Measures of Central Tendency</strong> — Where is the center?</li><li><strong>Measures of Dispersion</strong> — How spread out is the data?</li><li><strong>Measures of Shape</strong> — What does the distribution look like?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TkkWDALFk7Rqt8iUmuBiVA.webp" /></figure><h3>Measures of Central Tendency</h3><p>These metrics show where most values lie. Think of it as finding the <strong>“typical” value</strong>.</p><h3>1. Mean (Average)</h3><p>The <strong>mean</strong> is the arithmetic average. You add all the values and divide by the number of values.</p><p><strong>Formula</strong>:</p><p>x̄ = (1 / n) × Σ(xᵢ) for i = 1 to n <br><strong>Example</strong>:<br> Dataset: [10, 20, 30]<br> Mean = 10+20+303=20\frac{10+20+30}{3} = 20310+20+30​=20</p><p>Use it when the data is <strong>symmetrical and doesn’t have extreme outliers</strong>.</p><h3>2. Median</h3><p>The <strong>median</strong> is the middle value when the data is sorted.</p><ul><li>If the dataset has an odd number of values, median = middle value.</li><li>If it has an even number, median = average of the two middle values.</li></ul><p><strong>Example</strong>:<br> Dataset: [5, 8, 12, 15, 20] → Median = <strong>12</strong></p><p>Use it when the data is <strong>skewed or has outliers</strong> (like income data).</p><h3>3. Mode</h3><p>The <strong>mode</strong> is the value that appears <strong>most frequently</strong>.</p><p><strong>Example</strong>:<br> Dataset: [1, 2, 2, 3, 4, 4, 4, 5] → Mode = <strong>4</strong></p><p>Use it with <strong>categorical</strong> or <strong>discrete</strong> data where frequency matters.</p><h3>Measures of Dispersion</h3><p>Once you know the center, you need to know <strong>how spread out the values are</strong>.</p><h3>1. Range</h3><p>The <strong>range</strong> is the difference between the highest and lowest values.</p><p><strong>Formula</strong>:<br>Range = max(x) − min(x)<br><strong>Example</strong>:<br> Data = [3, 7, 10, 15] → Range = 15–3 = <strong>12</strong></p><p>It’s simple but sensitive to outliers.</p><h3>2. Variance</h3><p>Variance measures the <strong>average squared distance from the mean</strong>. It shows how the values deviate from the average.</p><p><strong>Sample Variance Formula</strong>:</p><p>s² = (1 / (n − 1)) × Σ(xᵢ − x̄)² for i = 1 to n</p><p>It gives you a feel for overall variability but is hard to interpret because it’s in <strong>squared units</strong>.</p><h3>3. Standard Deviation</h3><p>The <strong>standard deviation</strong> is the square root of the variance — and it’s more intuitive because it’s in the <strong>same unit as the data</strong>.</p><p><strong>Formula</strong>:</p><p>s = √s²<br><strong>Example</strong>:<br> If scores are clustered around the mean → low std dev<br> If scores are all over the place → high std dev</p><p>Standard deviation is used <strong>everywhere</strong> — from stock market volatility to quality control in manufacturing.</p><h3>4. Interquartile Range (IQR)</h3><p>IQR focuses on the <strong>middle 50%</strong> of the data and cuts off extreme values.</p><p><strong>Formula</strong>:</p><p>IQR = Q₃ − Q₁<br><strong>Example</strong>:<br> Data = [5, 10, 12, 14, 18, 20, 25]<br> Q1 = 10, Q3 = 20 → IQR = 10</p><p>IQR is used in <strong>box plots</strong> and <strong>outlier detection</strong>.</p><p>we covered the <strong>center</strong> (mean, median, mode) and the <strong>spread</strong> (range, standard deviation, IQR) of data — the two pillars of descriptive statistics.</p><p>But knowing just where the data lies and how much it varies isn’t enough.</p><blockquote><em>What if the data leans one way?<br> What if there are outliers?<br> Where do individual values stand in the crowd?</em></blockquote><p>That’s what <strong>Part 2</strong> is all about — exploring the <strong>shape</strong> of the distribution and the <strong>position of values</strong> using:</p><ul><li><strong>Skewness</strong></li><li><strong>Kurtosis</strong></li><li><strong>Z-Score</strong></li><li><strong>Percentiles</strong></li></ul><h3>Shape of the Distribution</h3><p>Understanding how your data is shaped helps you interpret averages and assess risks better.</p><h3>1. Skewness — How Lopsided Is the Data?</h3><p><strong>Skewness</strong> measures the <strong>asymmetry</strong> of a dataset.</p><h4>Formula (Sample Skewness):</h4><p>g₁ = [n / ((n − 1)(n − 2))] × Σ[(xᵢ − x̄) / s]³</p><h4>Interpretation:</h4><p>Skewness ValueMeaning 0 Symmetrical (normal)&gt; 0 Right-skewed (tail to right)&lt; 0 Left-skewed (tail to left)</p><h4>Real-World Example:</h4><ul><li><strong>Income data</strong>: Right-skewed — most people earn modestly, but a few are ultra-rich</li><li><strong>Test scores</strong>: Left-skewed — most students do well, few score very low</li></ul><p>Skewness affects whether the <strong>mean</strong> is a trustworthy average — in skewed data, <strong>median is better</strong>.</p><h3>2. Kurtosis — How Extreme Are the Extremes?</h3><p><strong>Kurtosis</strong> measures the <strong>“tailedness”</strong> of a dataset — how likely are extreme values?</p><h4>Formula (Excess Kurtosis):</h4><p>Kurtosis = [n(n + 1) / ((n − 1)(n − 2)(n − 3))] × Σ[(xᵢ − x̄) / s]⁴ <br> − [3(n − 1)² / ((n − 2)(n − 3))]</p><h4>🔍 Interpretation:</h4><p>TypeDescriptionTail Risk<strong>Mesokurtic</strong>Normal peak (like bell curve)Normal<strong>Leptokurtic</strong>Sharp peak, heavy tailsHigh → more outliers<strong>Platykurtic</strong>Flat peak, light tailsLow → fewer outliers</p><h4>Real-World Example:</h4><ul><li><strong>Stock returns</strong>: Leptokurtic → rare crashes/spikes</li><li><strong>Standard test results</strong>: Platykurtic → everyone scored similarly</li></ul><p><strong>Kurtosis = “Should I expect surprises?”</strong></p><h3>Position of Values in the Dataset</h3><h3>3. Z-Score — How Far From the Mean?</h3><p><strong>Z-score</strong> tells you how many standard deviations a value is from the mean.</p><h4>Formula:</h4><p>z = (x − x̄) / s<br>Example:</p><p>If you score 85 on a test where the mean is 70 and std dev is 10:</p><p>z = (85 − 70) / 10 = 1.5<br>→ Your score is <strong>1.5 standard deviations above average</strong></p><h4>Use Cases:</h4><ul><li><strong>Anomaly detection</strong> (z &gt; 3 is often flagged)</li><li><strong>Compare across different scales</strong></li><li><strong>Standardized test scoring</strong></li></ul><h3>4. Percentile — What % Are Below This Value?</h3><p><strong>Percentile</strong> tells you what percentage of the data is <strong>less than or equal to</strong> a given value.</p><h4>Example:</h4><p>If you’re in the <strong>90th percentile</strong> of income:</p><blockquote><em>You earn more than 90% of people.</em></blockquote><h4>Formula (Conceptual):</h4><p>Percentile Rank = (Number of values below x / Total number of values) × 100</p><h4>Use Cases:</h4><ul><li><strong>Test ranking</strong> (top 10%)</li><li><strong>Medical growth charts</strong> (baby weight percentile)</li><li><strong>Employee performance ranking</strong></li></ul><p>In next part we will start one by one, starting with <strong>Inferential Statistics .</strong></p><p>If you like the article then follow me on socials ,<br><strong><em>linkedin </em></strong>: <a href="https://www.linkedin.com/in/dilli-raj-timalsina/">https://www.linkedin.com/in/dilli-raj-timalsina/</a><br><strong><em>twitter </em></strong>: <a href="https://twitter.com/dillirajtweets">https://twitter.com/dillirajtweets</a><br><strong><em>github </em></strong>: <a href="https://github.com/Dilli-Raj-Timalsina">https://github.com/Dilli-Raj-Timalsina</a><br><em>resources : </em><a href="https://www.youtube.com/watch?v=zRUliXuwJCQ&amp;list=PLZoTAELRMXVMhVyr3Ri9IQ-t5QPBtxzJO">https://www.youtube.com/watch?v=zRUliXuwJCQ&amp;list=PLZoTAELRMXVMhVyr3Ri9IQ-t5QPBtxzJO</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baa61000060c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Statistics for Machine Learning: Part 1 — Foundations You Must Know .]]></title>
            <link>https://medium.com/@dillirajtimalsina354/statistics-for-machine-learning-part-1-foundations-you-must-know-0f6e58a881fa?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f6e58a881fa</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Sat, 24 May 2025 09:24:28 GMT</pubDate>
            <atom:updated>2025-05-24T09:24:28.217Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Statistics for Machine Learning: Part 1 — Foundations You Must Know .</strong></h3><h3>1. What is Statistics?</h3><p><strong>Statistics</strong> is the science of <strong>collecting</strong>, <strong>organizing</strong>, <strong>analyzing</strong>, and <strong>interpreting</strong> data to make decisions or draw conclusions under uncertainty.</p><p>In simple terms:</p><blockquote><strong><em>Statistics = Making sense of data.</em></strong></blockquote><p>Whether you’re trying to <strong>understand a trend</strong>, <strong>predict an outcome</strong>, or <strong>make a decision</strong>, statistics gives you the tools.</p><h3>2. Why is Statistics Used?</h3><p>Because <strong>raw data alone is useless</strong> unless you can interpret it. Here’s what stats helps you do:</p><h3>1. Understand Patterns in Data</h3><ul><li>Are sales rising or falling?</li><li>Is there a trend in temperature?</li><li>Are customer complaints increasing?</li></ul><p>Use: <strong>Descriptive statistics</strong> helps you summarize what’s happening.</p><h3>2. Make Predictions</h3><ul><li>Will this user click the ad?</li><li>Will this stock go up next week?</li><li>Will a patient respond to a treatment?</li></ul><p>Use: <strong>Inferential statistics</strong> lets you predict future behavior based on sample data.</p><h3>3. Make Data-Driven Decisions</h3><ul><li>Is Strategy A better than Strategy B?</li><li>Is the new product launch effective?</li><li>Is a medicine really curing people?</li></ul><p>Use: <strong>Hypothesis testing</strong> and <strong>A/B testing</strong> are statistical tools to guide decision-making.</p><h3>4. Deal with Uncertainty</h3><p>Life isn’t deterministic. Stats quantifies uncertainty with <strong>probabilities</strong>, <strong>confidence intervals</strong>, and <strong>distributions</strong>.</p><p>Use: Helps in <strong>risk assessment</strong>, <strong>forecasting</strong>, and <strong>model validation</strong>.</p><h3>5. Drive Machine Learning</h3><p>Machine learning is <strong>built on top of statistical principles</strong>:</p><ul><li>Regression → from statistical linear regression</li><li>Naive Bayes → from Bayes’ Theorem</li><li>Decision Trees → based on entropy and information gain (info theory = stats)</li></ul><p>Without stats, ML would just be a black box.</p><h3><strong>Main Domains / Types of Statistics</strong></h3><h3>1. Descriptive Statistics</h3><p>This is the <strong>summary layer</strong> of statistics — organizing and describing raw data.</p><h4>Tools:</h4><ul><li>Mean, median, mode</li><li>Standard deviation, variance</li><li>Charts: histograms, bar graphs, pie charts</li><li>Frequency distributions</li></ul><h4>Example:</h4><blockquote><em>An e-commerce site calculates the </em><strong><em>average order value</em></strong><em> from 10,000 sales records.</em></blockquote><h4>Use in ML:</h4><p>Used in <strong>Exploratory Data Analysis (EDA)</strong> to clean, visualize, and understand data before modeling.</p><h3>2. Inferential Statistics</h3><p>This is the <strong>decision-making</strong> branch of stats — making predictions, testing assumptions.</p><h4>Tools:</h4><ul><li>Hypothesis testing (t-test, z-test)</li><li>Confidence intervals</li><li>ANOVA</li><li>Chi-square test</li><li>p-values</li></ul><h4>Example:</h4><blockquote><em>A company tests if their </em><strong><em>new website design improves user engagement</em></strong><em> based on a sample of 500 users.</em></blockquote><h4>Use in ML:</h4><ul><li>A/B testing</li><li>Model evaluation</li><li>Checking if model results are statistically significant</li></ul><h3>3. Bayesian Statistics</h3><p>Instead of just calculating a result, Bayesian stats <strong>starts with a belief (prior)</strong> and <strong>updates it</strong> with data (likelihood).</p><h4>Tools:</h4><ul><li>Bayes’ Theorem</li><li>Posterior distributions</li><li>Markov Chain Monte Carlo (MCMC)</li></ul><h4>Example:</h4><blockquote><em>A spam filter uses </em><strong><em>Bayesian inference</em></strong><em> to decide if an email is spam based on prior word patterns.</em></blockquote><h4>Use in ML:</h4><ul><li>Naive Bayes classifier</li><li>Probabilistic models</li><li>Reinforcement learning</li></ul><h3>4. Multivariate Statistics</h3><p>This is about analyzing <strong>more than one variable at a time</strong> — useful when features in your data are interrelated.</p><h4>Tools:</h4><ul><li>Principal Component Analysis (PCA)</li><li>Factor Analysis</li><li>MANOVA</li><li>Canonical correlation</li></ul><h4>Example:</h4><blockquote><em>A researcher studies how </em><strong><em>income, education, and age</em></strong><em> together influence loan repayment behavior.</em></blockquote><h4>Use in ML:</h4><ul><li>Dimensionality reduction (PCA)</li><li>Feature selection</li><li>Clustering</li></ul><h3>5. Non-parametric Statistics</h3><p>Useful when your data doesn’t fit into a nice bell curve.</p><h4>Tools:</h4><ul><li>Wilcoxon test</li><li>Kruskal-Wallis test</li><li>Mann-Whitney U test</li></ul><h4>Example:</h4><blockquote><em>Comparing </em><strong><em>user ratings</em></strong><em> from two websites where data isn’t normally distributed.</em></blockquote><h4>Use in ML:</h4><ul><li>Robust models that don’t rely on distribution assumptions</li><li>Rank-based algorithms</li></ul><h3>6. Computational Statistics</h3><p>This branch uses programming to simulate and model data-heavy situations.</p><h4>Tools:</h4><ul><li>Bootstrapping</li><li>Monte Carlo simulations</li><li>Resampling techniques</li></ul><h4>Example:</h4><blockquote><em>Simulating thousands of possible </em><strong><em>stock price paths</em></strong><em> to calculate risk.</em></blockquote><h4>Use in ML:</h4><ul><li>Model validation</li><li>Cross-validation</li><li>Resampling imbalanced datasets</li></ul><p>In next part we will start one by one, starting with <strong>Descriptive Statistics .</strong></p><p>If you like the article then follow me on socials ,<br><strong><em>linkedin </em></strong>: <a href="https://www.linkedin.com/in/dilli-raj-timalsina/">https://www.linkedin.com/in/dilli-raj-timalsina/</a><br><strong><em>twitter </em></strong>: <a href="https://twitter.com/dillirajtweets">https://twitter.com/dillirajtweets</a><br><strong><em>github </em></strong>: <a href="https://github.com/Dilli-Raj-Timalsina">https://github.com/Dilli-Raj-Timalsina</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f6e58a881fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step JavaScript Build Process (from Code to Browser)]]></title>
            <link>https://medium.com/@dillirajtimalsina354/step-by-step-javascript-build-process-from-code-to-browser-4f7cd7720617?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f7cd7720617</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[bundle]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 04:49:49 GMT</pubDate>
            <atom:updated>2025-02-15T04:49:49.018Z</atom:updated>
            <content:encoded><![CDATA[<h3>Step 1: Writing Code (TypeScript/JSX/Modern JavaScript)</h3><p>When you write React code using <strong>TypeScript (.tsx)</strong> or modern <strong>ES6+ JavaScript</strong>, the browser <strong>cannot directly understand</strong> TypeScript or JSX. It needs to be converted into standard JavaScript.</p><p><strong>Example:</strong></p><pre>// App.tsx<br>const App = () =&gt; {<br>  return &lt;h1&gt;Hello, World!&lt;/h1&gt;;<br>};<br>export default App;</pre><ul><li>This contains <strong>JSX</strong> and <strong>TypeScript</strong> syntax.</li><li>It needs to be <strong>converted</strong> into <strong>JavaScript</strong> that the browser can understand.</li></ul><p><strong>Tool Used:</strong> ✅ <strong>TypeScript Compiler (</strong><strong>tsc)</strong> – Converts TypeScript to JavaScript.<br>✅ <strong>Babel</strong> – Transforms JSX into JavaScript.</p><h3>Step 2: Transpilation (Convert Code to Older JavaScript)</h3><p>Transpilation converts <strong>modern JavaScript (ES6+) or TypeScript</strong> into <strong>older JavaScript (ES5)</strong> so older browsers can run it.</p><p><strong>Example Before (ES6+ JavaScript):</strong></p><pre>const greet = (name) =&gt; `Hello, ${name}`;</pre><p><strong>After Transpilation (ES5 JavaScript):</strong></p><pre>var greet = function(name) {<br>  return &quot;Hello, &quot; + name;<br>};</pre><p><strong>Tools Used:</strong> ✅ <strong>Babel</strong> — Converts JSX &amp; modern JS to ES5.<br>✅ <strong>SWC or esbuild</strong> — Faster alternative to Babel.</p><p>🔹 <strong>How it Works?</strong></p><ul><li>Babel uses a config file (.babelrc or babel.config.js).</li><li>It reads the TypeScript/JSX code and <strong>transforms</strong> it into standard JavaScript.</li></ul><h3>Step 3: Polyfilling (Adding Missing Features for Older Browsers)</h3><p>Some JavaScript features (like Promise, fetch, Object.assign) do <strong>not exist</strong> in older browsers like IE11.<br><strong>Polyfills</strong> are small pieces of code that add these missing features.</p><p>🔹 <strong>Example:</strong></p><ul><li>Old browsers don’t support Promise, so a <strong>polyfill</strong> manually adds it:</li></ul><pre>if (!window.Promise) {<br>  window.Promise = function(executor) {<br>    // Custom implementation for Promise<br>  };<br>}</pre><p><strong>Tools Used:</strong> ✅ <strong>core-js</strong> — Provides polyfills for modern features.<br>✅ <strong>regenerator-runtime</strong> — Polyfills async/await.<br>✅ <strong>@babel/polyfill</strong> (deprecated) — Used before core-js.</p><h3>Step 4: Bundling (Combine Multiple Files into One)</h3><p>Instead of loading <strong>many separate JavaScript files</strong>, bundling <strong>combines them into a single file</strong> for efficiency.</p><p>🔹 <strong>Example:</strong></p><ul><li>Suppose you have these files:</li></ul><p>📂 <strong>utils.js</strong></p><pre>export function add(a, b) {<br>  return a + b;<br>}</pre><p>📂 <strong>index.js</strong></p><pre>import { add } from &quot;./utils.js&quot;;<br>console.log(add(2, 3));</pre><p>After <strong>bundling</strong>, these two files will be <strong>merged into one</strong>.</p><p><strong>Tools Used:</strong> ✅ <strong>Webpack</strong> — Most common bundler.<br>✅ <strong>Vite</strong> — Faster alternative to Webpack.<br>✅ <strong>Rollup</strong> — Used for libraries like React.<br>✅ <strong>Parcel</strong> — Zero-config bundler.</p><p>🔹 <strong>How it Works?</strong></p><ul><li>The bundler analyzes dependencies and <strong>merges</strong> files into one output file (e.g., bundle.js).</li></ul><h3>Step 5: Tree Shaking (Remove Unused Code)</h3><p>Tree shaking <strong>removes unused imports and functions</strong> to reduce bundle size.</p><p>🔹 <strong>Example (Before Optimization):</strong></p><pre>export function add(a, b) { return a + b; }<br>export function subtract(a, b) { return a - b; }</pre><pre>import { add } from &quot;./math.js&quot;;<br>console.log(add(5, 10));</pre><p>Here, we <strong>never use </strong><strong>subtract()</strong>, but without tree shaking, the entire file is included in the bundle.</p><p>🔹 <strong>After Tree Shaking:</strong></p><ul><li>The final bundle will <strong>only include </strong><strong>add()</strong> because subtract() is not used.</li></ul><p><strong>Tools Used:</strong> ✅ <strong>Webpack + Terser</strong> — Removes unused code.<br>✅ <strong>Rollup</strong> — Built-in tree shaking.<br>✅ <strong>esbuild</strong> — Super fast bundling + tree shaking.</p><h3>Step 6: Minification (Make the Code Smaller)</h3><p>Minification removes unnecessary spaces, comments, and renames variables <strong>to reduce file size</strong>.</p><p>🔹 <strong>Example (Before Minification):</strong></p><pre>function addNumbers(a, b) {<br>    return a + b;<br>}<br>console.log(addNumbers(5, 10));</pre><p>🔹 <strong>After Minification:</strong></p><pre>function a(a,b){return a+b}console.log(a(5,10));</pre><p><strong>Tools Used:</strong> ✅ <strong>Terser</strong> — Minifies JS.<br>✅ <strong>UglifyJS</strong> — Another minifier.<br>✅ <strong>esbuild</strong> — Also handles minification.</p><h3>Step 7: Code Splitting (Load Only What’s Needed)</h3><p>Instead of loading everything at once, code splitting <strong>breaks the bundle into smaller pieces</strong>.</p><p>🔹 <strong>Example (Before Code Splitting):</strong></p><pre>import Dashboard from &quot;./Dashboard&quot;;</pre><p>🔹 <strong>After Code Splitting (Lazy Load):</strong></p><pre>const Dashboard = React.lazy(() =&gt; import(&quot;./Dashboard&quot;));</pre><p>Now, the Dashboard component <strong>only loads when needed</strong> (reducing initial load time).</p><p><strong>Tools Used:</strong> ✅ <strong>Webpack</strong> — Supports dynamic imports.<br>✅ <strong>React.lazy()</strong> — Loads components dynamically.<br>✅ <strong>Next.js Automatic Code Splitting</strong> — Splits code at the page level.</p><h3>Step 8: Running Development Server (Hot Reloading)</h3><p>When you run npm run dev, a <strong>development server</strong> starts.</p><p>🔹 <strong>What Happens?</strong></p><ol><li>Watches for file changes.</li><li>Recompiles only the changed file (Hot Module Replacement).</li><li>Refreshes the browser instantly.</li></ol><p><strong>Tools Used:</strong> ✅ <strong>Webpack Dev Server</strong> — For Webpack projects.<br>✅ <strong>Vite</strong> — Super fast dev server.<br>✅ <strong>Next.js Server</strong> — Handles SSR &amp; API routes.</p><h3>🚀 Final Summary: The Full Flow</h3><h3>1️⃣ Writing Code</h3><ul><li>You write TypeScript (.tsx) and modern JavaScript (.js).</li></ul><h3>2️⃣ Transpilation</h3><ul><li>Babel converts JSX and ES6+ to ES5 JavaScript.</li></ul><h3>3️⃣ Polyfilling</h3><ul><li>core-js adds missing features for old browsers.</li></ul><h3>4️⃣ Bundling</h3><ul><li>Webpack/Vite combines multiple files into one.</li></ul><h3>5️⃣ Tree Shaking</h3><ul><li>Unused functions and imports are removed.</li></ul><h3>6️⃣ Minification</h3><ul><li>Terser reduces the file size by removing spaces/comments.</li></ul><h3>7️⃣ Code Splitting</h3><ul><li>React.lazy() and Webpack split large files for faster loading.</li></ul><h3>8️⃣ Running Dev Server</h3><ul><li>Vite/Webpack Dev Server enables hot reloading for fast development.</li></ul><h3>Final Thought</h3><p>All these steps ensure that: ✅ Your JavaScript code runs <strong>on all browsers</strong>.<br>✅ The <strong>smallest possible file size</strong> is shipped.<br>✅ The <strong>app loads fast and efficiently</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f7cd7720617" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript 0 to 100 : Factory, Decorators and Meta Programming . (Part 4)]]></title>
            <link>https://medium.com/@dillirajtimalsina354/typescript-0-to-100-factory-decorators-and-meta-programming-part-4-82eeb7c1864c?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/82eeb7c1864c</guid>
            <category><![CDATA[decorators]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[factory-func]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 04:46:57 GMT</pubDate>
            <atom:updated>2024-10-24T05:56:27.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Typescript 0 to 100 : Factory functions and Decorator syntax (Part 4) .</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i6gJarUa2lXVqaPn" /></figure><h3>1. What is a Factory Function?</h3><p>A factory function is simply a function that creates and returns an object. It doesn’t require using new, and you can customize the returned object in any way.</p><p>Here’s a basic example of a factory function:</p><pre>function createUser(name, age) {<br>  return {<br>    name,<br>    age,<br>    greet() {<br>      console.log(`Hello, my name is ${name} and I am ${age} years old.`);<br>    }<br>  };<br>}<br><br>const user1 = createUser(&#39;Alice&#39;, 30);<br>const user2 = createUser(&#39;Bob&#39;, 25);<br><br>user1.greet(); // &quot;Hello, my name is Alice and I am 30 years old.&quot;<br>user2.greet(); // &quot;Hello, my name is Bob and I am 25 years old.&quot;</pre><p>In this example, createUser returns a new object each time it’s called. Each object has its own name, age, and greet method. This is a simple, flexible way to create new objects without using class or new.</p><h3>Advantages of Factory Functions</h3><p>Factory functions offer several advantages over classes and constructor functions:</p><ol><li><strong>No Need for </strong><strong>new Keyword</strong>: You avoid issues that come with forgetting to use new with constructor functions.</li><li><strong>Encapsulation</strong>: You can hide internal logic or data inside closures, making it private to the function and inaccessible from the outside.</li><li><strong>More Readable and Flexible</strong>: They’re more straightforward than class-based inheritance, and you have more control over the returned object.</li></ol><h3>Decorator Syntax in JavaScript</h3><p>Decorators in JavaScript are a special kind of syntax used to modify the behavior of classes, methods, or properties. They allow you to apply reusable functionality to code in a clean and declarative way. Although the decorator syntax is still in the <strong>proposal stage</strong> in JavaScript (as of 2024), it’s widely used in many frameworks (like Angular) and supported by TypeScript and Babel.</p><p>Decorators are essentially <strong>higher-order functions</strong> that can be applied to <strong>classes</strong>, <strong>methods</strong>, <strong>accessors</strong>, <strong>properties</strong>, or <strong>parameters</strong> to modify their behavior.</p><h3>How Decorators Work</h3><p>A <strong>decorator</strong> is a function that is applied to a class or a class member (such as a method, property, or accessor) to extend or modify its behavior. Decorators are typically prefixed with the @ symbol.</p><p>Here’s a quick breakdown of how decorators can be applied:</p><ol><li><strong>Class Decorators</strong>: Modify or replace a class definition.</li><li><strong>Method Decorators</strong>: Modify the behavior of class methods.</li><li><strong>Accessor Decorators</strong>: Modify getter/setter behavior.</li><li><strong>Property Decorators</strong>: Alter property initialization.</li><li><strong>Parameter Decorators</strong>: Modify method parameters.</li></ol><h3>Enabling Decorators</h3><p>As decorators are still in the proposal stage, you need to enable them using either <strong>Babel</strong> or <strong>TypeScript</strong>.</p><h3>1. Class Decorators</h3><p>A class decorator is applied to the entire class definition. It receives the class constructor as an argument and can either modify or return a new class. In this example, addTimestamp is a class decorator that enhances the Person class by adding a timestamp property to it.</p><pre>function addTimestamp(constructor) {<br>  return class extends constructor {<br>    timestamp = new Date();<br>  };<br>}<br><br>@addTimestamp<br>class Person {<br>  constructor(name) {<br>    this.name = name;<br>  }<br>}<br><br>const person = new Person(&#39;Alice&#39;);<br>console.log(person.timestamp); // Outputs the current date and time</pre><h3><strong>2. Method Decorators</strong></h3><p>A <strong>method decorator</strong> is a function applied to a class method that allows you to modify or extend the behavior of that method. It operates by wrapping the original method or replacing it entirely. The method decorator receives three key arguments:</p><ol><li><strong>target</strong>: The object to which the method belongs (usually the class&#39;s prototype).</li><li><strong>key</strong>: The name of the method being decorated.</li><li><strong>descriptor</strong>: The method&#39;s property descriptor, which gives you control over the method&#39;s behavior (e.g., value, writable, configurable, etc.).</li></ol><pre>function logMethod(target, key, descriptor) {<br>  console.log(`Target:`, target);<br>  console.log(`Method: ${key}`);<br>  console.log(`Descriptor:`, descriptor);<br><br>  const originalMethod = descriptor.value;<br><br>  descriptor.value = function (...args) {<br>    console.log(`Calling method: ${key} with args:`, args);<br>    const result = originalMethod.apply(this, args);<br>    console.log(`Result of ${key}:`, result);<br>    return result;<br>  };<br><br>  return descriptor;<br>}<br><br>class Calculator {<br>  @logMethod<br>  add(a, b) {<br>    return a + b;<br>  }<br>}<br><br>const calculator = new Calculator();<br>calculator.add(5, 10);</pre><p><strong>output :</strong></p><pre>Target: {constructor: ƒ, add: ƒ}<br>Method: add<br>Descriptor: {value: ƒ, writable: true, enumerable: false, configurable: true}<br>Calling method: add with args: [5, 10]<br>Result of add: 15</pre><h3>3. Property Decorators in JavaScript</h3><p>A <strong>property decorator</strong> is used to modify or observe the behavior of a class property. Unlike method decorators, property decorators don’t have access to the property descriptor because properties don’t have descriptors at the time of definition.</p><p>Here’s how property decorators work:</p><h3>Basic Example of a Property Decorator:</h3><pre>function logEmailChange(target, key) {<br>  let value = target[key];<br><br>  const getter = () =&gt; {<br>    console.log(`Getting value of ${key}: ${value}`);<br>    return value;<br>  };<br><br>  const setter = (newValue) =&gt; {<br>    console.log(`Updating ${key} from ${value} to ${newValue}`);<br>    value = newValue;<br>  };<br><br>  Object.defineProperty(target, key, {<br>    get: getter,<br>    set: setter,<br>    enumerable: true,<br>    configurable: true<br>  });<br>}<br><br>class User {<br>  @logEmailChange<br>  email;<br><br>  constructor(email) {<br>    this.email = email;<br>  }<br>}<br><br>const user = new User(&#39;initial@example.com&#39;);<br>user.email = &#39;new@example.com&#39;;  // Logs email change<br>console.log(user.email);         // Logs the current email value</pre><h3>Key Points:</h3><ul><li><strong>target</strong>: The class prototype (User.prototype).</li><li><strong>key</strong>: The property name (email).</li></ul><h3>Expected Output:</h3><pre>Updating email from initial@example.com to new@example.com<br>Getting value of email: new@example.com</pre><h3>4. Parameter Decorators</h3><p>A <strong>parameter decorator</strong> is used to observe or manipulate metadata about the parameters of a method in a class. It allows you to log or modify information about specific parameters when a method is invoked.</p><h3>Key Arguments in Parameter Decorators:</h3><ol><li><strong>target</strong>: The prototype of the class (for instance methods) or the constructor (for static methods).</li><li><strong>key</strong>: The name of the method where the parameter is located.</li><li><strong>index</strong>: The index of the parameter being decorated (0-based).</li></ol><pre>function logParameter(target, key, index) {<br>  console.log(`Target: ${target.constructor.name}`);<br>  console.log(`Method: ${key}`);<br>  console.log(`Parameter index: ${index}`);<br>}<br><br>class User {<br>  updateUser(@logParameter name, age) {<br>    console.log(`Updating user ${name} with age ${age}`);<br>  }<br>}<br><br>const user = new User();<br>user.updateUser(&#39;Alice&#39;, 25);</pre><h3>Logs Explanation:</h3><ol><li><strong>target</strong>: The prototype of User (since updateUser is an instance method).</li><li><strong>key</strong>: The name of the method, updateUser.</li><li><strong>index</strong>: The index of the decorated parameter (0, meaning the first parameter, name).</li></ol><pre>Target: User<br>Method: updateUser<br>Parameter index: 0<br>Updating user Alice with age 25</pre><h3>Conclusion</h3><p>We’ve explored <strong>parameter decorators</strong> in JavaScript, understanding how they provide insights into method parameters by logging the target, key, and index. Decorators allow us to cleanly observe, log, or manipulate method behavior and parameters, leading to more modular and reusable code.</p><p>Parameter decorators are a powerful tool for <strong>metaprogramming</strong>, giving you fine-grained control over how parameters are processed within a method.</p><p>If you like the article then follow me on socials ,<br><strong><em>linkedin </em></strong>: <a href="https://www.linkedin.com/in/dilli-raj-timalsina/">https://www.linkedin.com/in/dilli-raj-timalsina/</a><br><strong><em>twitter </em></strong>: <a href="https://twitter.com/dillirajtweets">https://twitter.com/dillirajtweets</a><br><strong><em>github </em></strong>: <a href="https://github.com/Dilli-Raj-Timalsina">https://github.com/Dilli-Raj-Timalsina</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82eeb7c1864c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: Typescript Generics .]]></title>
            <link>https://medium.com/@dillirajtimalsina354/part-3-typescript-generics-3ce5163a1c90?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ce5163a1c90</guid>
            <category><![CDATA[typescript-generi]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[advanced-typescript]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 09:33:53 GMT</pubDate>
            <atom:updated>2024-10-25T01:55:16.844Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 3: Typescript Generics( the giants ) .</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*Y21cdo1SGHJ0hFwd.png" /></figure><p>In this article we are going to cover some of the grand advanced typescript topics so please go throught the part 1 and part 2 of 0 to 100 typescript series . <br>part 1: <a href="https://medium.com/@dillirajtimalsina354/typescript-0-to-100-part-1-0c3302345eb1">https://medium.com/@dillirajtimalsina354/typescript-0-to-100-part-1-0c3302345eb1</a><br>part 2: <a href="https://medium.com/@dillirajtimalsina354/advanced-typescript-exploring-utility-types-and-constructs-part-2-088fba91da0a">https://medium.com/@dillirajtimalsina354/advanced-typescript-exploring-utility-types-and-constructs-part-2-088fba91da0a</a></p><p><strong>Generics</strong> in TypeScript allow you to create reusable components that work with a variety of data types instead of a single one. Generics provide a way to capture the type of an argument passed to a function, class, or interface and use that information to define the rest of the entity’s type structure. They help in writing more flexible and type-safe code.</p><h3>Why Use Generics?</h3><p>Without generics, you’d typically write specific implementations for different types, which can lead to redundancy. Generics solve this by allowing us to write a function, class, or interface that works for any type while maintaining type safety.</p><h3>1. Generic Functions</h3><p>Generics allow you to define functions that can work with different types while maintaining strong type checking.</p><h4>Example: A Generic Identity Function</h4><p>The following function simply returns the value passed to it. Without generics, you would have to create separate functions for each type.</p><pre>function identity&lt;T&gt;(value: T): T {<br>  return value;<br>}<br><br>console.log(identity&lt;string&gt;(&quot;Hello&quot;));  // Output: &quot;Hello&quot;<br>console.log(identity&lt;number&gt;(123));      // Output: 123</pre><p>Here, T is a generic type variable that can represent any type. When you call identity, TypeScript infers the type based on the argument or you can specify it explicitly.</p><h4>Inference in Generics</h4><p>TypeScript can often infer the type of the generic parameter based on the arguments:</p><pre>console.log(identity(&quot;World&quot;)); // TypeScript infers T as `string`</pre><h3>2. Generic Constraints</h3><p>Sometimes, you want to restrict the kinds of types that can be used with a generic. You can achieve this by using <strong>constraints</strong>.</p><h4>Example: Generic with a Constraint</h4><p>We can constrain a generic type to ensure it has certain properties. Here, the constraint T extends HasLength ensures that T must have a length property.</p><pre>interface HasLength {<br>  length: number;<br>}<br><br>function logLength&lt;T extends HasLength&gt;(item: T): T {<br>  console.log(item.length);<br>  return item;<br>}<br><br>logLength(&quot;Hello&quot;);        // Works: string has a length property<br>logLength([1, 2, 3]);      // Works: array has a length property<br>// logLength(123);         // Error: number doesn&#39;t have a length property</pre><h3>3. Generic Classes</h3><p>Generics also work with classes. You can use generics to create classes that can work with multiple types.</p><h4>Example: A Generic Stack Class</h4><p>Here’s an example of a stack class that works with any data type: This stack class can store any type of data, and the type is maintained throughout.</p><pre>class Stack&lt;T&gt; {<br>  private items: T[] = [];<br><br>  push(item: T) {<br>    this.items.push(item);<br>  }<br><br>  pop(): T | undefined {<br>    return this.items.pop();<br>  }<br><br>  peek(): T | undefined {<br>    return this.items[this.items.length - 1];<br>  }<br>}<br><br>const numberStack = new Stack&lt;number&gt;();<br>numberStack.push(10);<br>numberStack.push(20);<br>console.log(numberStack.pop()); // Output: 20<br><br>const stringStack = new Stack&lt;string&gt;();<br>stringStack.push(&quot;a&quot;);<br>stringStack.push(&quot;b&quot;);<br>console.log(stringStack.pop()); // Output: &quot;b&quot;</pre><h3>4. Generic Interfaces</h3><p>Just like functions and classes, interfaces can also use generics. This allows you to define flexible interfaces that work with multiple types.</p><h4>Example: A Generic Interface</h4><p>Here, the interface KeyValuePair&lt;K, V&gt; accepts two generic types, K (for the key) and V (for the value), allowing you to create different kinds of key-value pairs.</p><pre>interface KeyValuePair&lt;K, V&gt; {<br>  key: K;<br>  value: V;<br>}<br><br>const kv1: KeyValuePair&lt;string, number&gt; = { key: &quot;age&quot;, value: 30 };<br>const kv2: KeyValuePair&lt;number, boolean&gt; = { key: 1, value: true };</pre><h3>5. Generic Constraints with keyof</h3><p>Generics can be constrained to a specific set of keys using the keyof operator.</p><h4>Example: Using keyof with Generics</h4><p>In this example, K extends keyof T ensures that the key K must be a valid property key of the object T.</p><pre>function getProperty&lt;T, K extends keyof T&gt;(obj: T, key: K): T[K] {<br>  return obj[key];<br>}<br><br>const person = { name: &quot;Alice&quot;, age: 25 };<br>console.log(getProperty(person, &quot;name&quot;)); // Output: &quot;Alice&quot;<br>// console.log(getProperty(person, &quot;address&quot;)); // Error: &quot;address&quot; does not exist on type &#39;Person&#39;</pre><h3>6. Default Generic Types</h3><p>You can provide default values for generic parameters. This is useful when you want the generic to fall back to a default type if none is provided.</p><h4>Example: Default Type in Generics</h4><p>In the example above, if no type argument is provided, T defaults to string.</p><pre>function createArray&lt;T = string&gt;(length: number, value: T): T[] {<br>  return Array(length).fill(value);<br>}<br><br>const strArray = createArray(3, &quot;hello&quot;); // Type inferred as string[]<br>const numArray = createArray&lt;number&gt;(3, 100); // Explicit type number[]</pre><h3>7. Generic Type Aliases</h3><p>Type aliases can also be generic, allowing you to define flexible types.</p><h4>Example: Generic Type Alias</h4><p>In this example, ResponseData&lt;T&gt; allows you to define a flexible type that can wrap any data type in the data field.</p><pre>type ResponseData&lt;T&gt; = {<br>  data: T;<br>  status: number;<br>};<br><br>const response: ResponseData&lt;string&gt; = {<br>  data: &quot;Hello World&quot;,<br>  status: 200,<br>};</pre><p><strong><em>Hum !this much for today, there are many super advanced topics like generics in factories , generics in decorator sytax etc. which we will discuss in another article !<br>1 bonus tips for typescript above ^5 version .</em></strong></p><h3>Tip : Template Literal Types</h3><p>Template literal types allow you to create new string literal types by combining union types with literal types. This is useful for constructing complex string-based types.</p><pre>type Event = &quot;click&quot; | &quot;scroll&quot; | &quot;mousemove&quot;;<br>type EventMessage = `on${Capitalize&lt;Event&gt;}`;<br><br>let event: EventMessage;<br>event = &quot;onClick&quot;;       // Valid<br>event = &quot;onScroll&quot;;      // Valid<br>event = &quot;onMousemove&quot;;   // Valid</pre><p>Consider a scenario where you’re developing an application that uses a strict conventions for its API endpoints or routes. You might want to describe these paths using template literal types to ensure that your types are aligned with the expected structure of the API.</p><p>Here’s how you could define types for a simple API with some routes:</p><pre>type UserId = `${number}`;<br>type ApiEndpoint = `/users/${UserId}` | `/posts/${number}` | `/comments/${number}`;<br><br>function fetchApi(endpoint: ApiEndpoint) {<br>    // Simulated fetching logic<br>    console.log(`Fetching from ${endpoint}`);<br>}<br><br>// Correct usage:<br>fetchApi(&#39;/users/123&#39;); // Valid<br>fetchApi(&#39;/posts/456&#39;); // Valid<br>fetchApi(&#39;/comments/789&#39;); // Valid<br><br>// Incorrect usage:<br>fetchApi(&#39;/users/abc&#39;); // Error: Argument of type &#39;&quot;abc&quot;&#39; is not assignable to parameter of type &#39;ApiEndpoint&#39;.</pre><p>If you like the article then follow me on socials ,<br><strong><em>linkedin </em></strong>: <a href="https://www.linkedin.com/in/dilli-raj-timalsina/">https://www.linkedin.com/in/dilli-raj-timalsina/</a><br><strong><em>twitter </em></strong>: <a href="https://twitter.com/dillirajtweets">https://twitter.com/dillirajtweets</a><br><strong><em>github </em></strong>: <a href="https://github.com/Dilli-Raj-Timalsina">https://github.com/Dilli-Raj-Timalsina</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ce5163a1c90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced TypeScript: Exploring Utility Types and Constructs (Part 2)]]></title>
            <link>https://medium.com/@dillirajtimalsina354/advanced-typescript-exploring-utility-types-and-constructs-part-2-088fba91da0a?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/088fba91da0a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[advanced-typescript]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 06:47:23 GMT</pubDate>
            <atom:updated>2024-10-24T06:14:07.795Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PmuHX4I6lBc6I1hu" /></figure><p>Continuing from the previous article, we will now dive deeper into advanced TypeScript types such as <strong>union</strong>, <strong>intersection</strong>, and essential utility types like <strong>Omit</strong>, <strong>Pick</strong>, <strong>Readonly</strong>, and more. These types offer powerful ways to manipulate and shape types in your TypeScript code, allowing for greater flexibility and stronger type safety.</p><h3>1. Union Types</h3><p>As discussed in the previous article, <strong>union types</strong> allow a value to be one of several possible types. It’s useful when a variable or function can take multiple types. Union types improve flexibility by letting you define broader types but still maintain control over the set of valid types.</p><pre>let id: string | number;<br>id = &quot;123&quot;;  // Valid<br>id = 456;    // Valid</pre><h3>2. Intersection Types</h3><p><strong>Intersection types</strong> combine multiple types into one. A value of an intersection type must satisfy all the included types, making it useful for combining object types or ensuring that an object has multiple shapes. Intersection types are often used to create more complex types by merging multiple types into one.</p><pre>interface Name {<br>  name: string;<br>}<br><br>interface Age {<br>  age: number;<br>}<br><br>type Person = Name &amp; Age;<br><br>const person: Person = {<br>  name: &quot;Alice&quot;,<br>  age: 30,  // Must have both properties from Name and Age<br>};</pre><h3>3. Pick Utility Type</h3><p>The Pick&lt;Type, Keys&gt; utility type creates a new type by <strong>picking</strong> a subset of properties from another type. It&#39;s useful when you want to limit or focus on specific properties of a type. With Pick, you can extract only the necessary properties from a larger type.</p><pre>interface User {<br>  id: number;<br>  name: string;<br>  email: string;<br>}<br><br>type UserPreview = Pick&lt;User, &quot;id&quot; | &quot;name&quot;&gt;;<br><br>const user: UserPreview = {<br>  id: 1,<br>  name: &quot;John&quot;,  // Only &quot;id&quot; and &quot;name&quot; are picked<br>};</pre><h3>4. Omit Utility Type</h3><p>The Omit&lt;Type, Keys&gt; utility type is the opposite of Pick. It creates a new type by <strong>excluding</strong> a set of properties from another type. Omit is especially useful when you want to remove certain fields from an existing type to create a more specific type.</p><pre>interface User {<br>  id: number;<br>  name: string;<br>  email: string;<br>}<br><br>type UserWithoutEmail = Omit&lt;User, &quot;email&quot;&gt;;<br><br>const user: UserWithoutEmail = {<br>  id: 1,<br>  name: &quot;John&quot;,  // &quot;email&quot; is omitted<br>};</pre><h3>5. Readonly Utility Type</h3><p>The Readonly&lt;Type&gt; utility type makes all properties of a type immutable, meaning they cannot be modified after initialization. Readonly is useful when you want to enforce immutability in your data structures, ensuring that certain objects remain unchanged after creation.</p><pre>interface User {<br>  id: number;<br>  name: string;<br>}<br><br>const user: Readonly&lt;User&gt; = {<br>  id: 1,<br>  name: &quot;John&quot;,<br>};<br><br>// user.id = 2;  // Error: Cannot assign to &#39;id&#39; because it is a read-only property</pre><h3>6. Partial Utility Type</h3><p>The Partial&lt;Type&gt; utility type makes all properties of a type optional, allowing you to create flexible versions of an existing type. Partial is often used in scenarios like updates or configuration objects where you may not need to provide every property.</p><pre>interface User {<br>  id: number;<br>  name: string;<br>  email: string;<br>}<br><br>const userUpdate: Partial&lt;User&gt; = {<br>  name: &quot;John Updated&quot;,  // Optional properties<br>};</pre><h3>7. Required Utility Type</h3><p>The Required&lt;Type&gt; utility type makes all properties of a type <strong>mandatory</strong>. This is the opposite of Partial. Required is useful when you want to enforce that all properties must be provided in a type.</p><pre>interface User {<br>  id?: number;<br>  name?: string;<br>}<br><br>const user: Required&lt;User&gt; = {<br>  id: 1,<br>  name: &quot;John&quot;,  // All properties are now required<br>};</pre><h3>8. Record Utility Type</h3><p>As discussed earlier, the Record&lt;Keys, Type&gt; utility type creates an object type where all keys are of type Keys, and the values are of type Type. Record is often used when you need to map a set of keys to specific values.</p><pre>type Role = &quot;admin&quot; | &quot;user&quot; | &quot;guest&quot;;<br>type Permissions = Record&lt;Role, boolean&gt;;<br><br>const userPermissions: Permissions = {<br>  admin: true,<br>  user: true,<br>  guest: false,<br>};</pre><h3>9. Exclude Utility Type</h3><p>The Exclude&lt;Type, ExcludedUnion&gt; utility type removes types from a union. This is useful when you want to refine a union type by excluding certain cases.</p><pre>type Status = &quot;active&quot; | &quot;inactive&quot; | &quot;pending&quot;;<br>type ActiveStatus = Exclude&lt;Status, &quot;pending&quot;&gt;;  // Removes &quot;pending&quot;</pre><h3>10. Extract Utility Type</h3><p>The Extract&lt;Type, Union&gt; utility type extracts a subset of types from a union that match a certain condition. Extract allows you to filter union types to include only the types you need.</p><pre>type Status = &quot;active&quot; | &quot;inactive&quot; | &quot;pending&quot;;<br>type ActiveOrPending = Extract&lt;Status, &quot;active&quot; | &quot;pending&quot;&gt;;  // Only includes &quot;active&quot; and &quot;pending&quot;</pre><h3>11. Union Types and Intersection Types Combined</h3><p>You can combine <strong>union</strong> and <strong>intersection</strong> types to create more complex type structures. This approach gives you the flexibility to create types that require a mix of properties but allow for different combinations of others.</p><pre>interface Name {<br>  name: string;<br>}<br><br>interface Email {<br>  email: string;<br>}<br><br>type Contact = (Name | Email) &amp; { id: number };<br><br>const contact1: Contact = { id: 1, name: &quot;Alice&quot; };<br>const contact2: Contact = { id: 2, email: &quot;alice@example.com&quot; };<br>// Must have &quot;id&quot;, and can have either &quot;name&quot; or &quot;email&quot;</pre><h3>12. NonNullable Utility Type</h3><p>The NonNullable&lt;Type&gt; utility type removes null and undefined from a type.This excludes null and undefined, leaving only string.</p><pre>type MaybeString = string | null | undefined;<br>type NonNullableString = NonNullable&lt;MaybeString&gt;;  // Result: string</pre><h3>13. keyof Types</h3><p>The keyof operator in TypeScript is used to create a union of all the keys in a type. It’s useful when you need to reference the keys of an object type dynamically.</p><pre>type Person = {<br>  name: string;<br>  age: number;<br>  location: string;<br>};<br><br>type PersonKeys = keyof Person;  // Result: &quot;name&quot; | &quot;age&quot; | &quot;location&quot;</pre><p>This produces a union of all the keys (&quot;name&quot; | &quot;age&quot; | &quot;location&quot;), which can be used to ensure type safety when accessing properties dynamically.</p><pre>function getValue&lt;T, K extends keyof T&gt;(obj: T, key: K): T[K] {<br>  return obj[key];<br>}<br><br>const person = { name: &#39;John&#39;, age: 30, location: &#39;NYC&#39; };<br>const name = getValue(person, &#39;name&#39;);  // Type-safe access, name: string</pre><h3>14. Index Types</h3><p>Index types allow you to look up the type of properties using the keyof operator. This is useful for extracting types of specific keys dynamically. This is helpful for enforcing or checking the type of specific properties of an object.</p><pre>type Person = {<br>  name: string;<br>  age: number;<br>};<br><br>type NameType = Person[&#39;name&#39;];  // Result: string<br>type AgeType = Person[&#39;age&#39;];    // Result: number</pre><h3>15. Mapped Types</h3><p>Mapped types allow you to create new types by transforming properties of an existing type. This is done by iterating over each property of a type using keyof and applying modifications.</p><h4>Example: Making All Properties Optional</h4><pre>type Person = {<br>  name: string;<br>  age: number;<br>};<br><br>type PartialPerson = {<br>  [K in keyof Person]?: Person[K];<br>};<br>// Result: { name?: string; age?: number }</pre><h4>Example: Readonly Properties</h4><pre>type ReadonlyPerson = {<br>  [K in keyof Person]: Readonly&lt;Person[K]&gt;;<br>};<br>// Result: { readonly name: string; readonly age: number }</pre><h3>16. TypeScript Casting</h3><p>TypeScript provides ways to cast types when the type system needs help in narrowing or converting a type.</p><h4>Type Assertion with as</h4><p>You can cast a variable from one type to another using the as keyword.</p><pre>let value: unknown = &quot;Hello&quot;;<br>let strLength: number = (value as string).length;</pre><h4>Type Assertion with Angle Brackets</h4><p>In non-TSX files, you can also use angle brackets for casting. This is equivalent to the as keyword.</p><pre>let value: unknown = &quot;Hello&quot;;<br>let strLength: number = (&lt;string&gt;value).length;</pre><h3>16. TypeScript Classes</h3><p>TypeScript classes bring object-oriented features with type safety. You can define properties, methods, and access modifiers such as public, private, and protected.</p><pre>class Person {<br>  name: string;<br>  age: number;<br><br>  constructor(name: string, age: number) {<br>    this.name = name;<br>    this.age = age;<br>  }<br><br>  greet(): string {<br>    return `Hello, my name is ${this.name}.`;<br>  }<br>}</pre><h4>Access Modifiers</h4><ul><li>public: accessible anywhere (default).</li><li>private: accessible only within the class.</li><li>protected: accessible within the class and subclasses.</li></ul><p>These types and constructs form the foundation of type safety and structure in TypeScript, making it a powerful tool for writing reliable, scalable code. In the next part, more advanced utility types will be discussed.</p><p>If you like the article then follow me on socials ,<br><strong><em>linkedin </em></strong>: <a href="https://www.linkedin.com/in/dilli-raj-timalsina/">https://www.linkedin.com/in/dilli-raj-timalsina/</a><br><strong><em>twitter </em></strong>: <a href="https://twitter.com/dillirajtweets">https://twitter.com/dillirajtweets</a><br><strong><em>github </em></strong>: <a href="https://github.com/Dilli-Raj-Timalsina">https://github.com/Dilli-Raj-Timalsina</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088fba91da0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript 0 to 100 part 1 .]]></title>
            <link>https://medium.com/@dillirajtimalsina354/typescript-0-to-100-part-1-0c3302345eb1?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c3302345eb1</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[typescript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 02:40:28 GMT</pubDate>
            <atom:updated>2024-10-24T06:14:41.181Z</atom:updated>
            <content:encoded><![CDATA[<h3>Typescript 0 to 100 (part 1) .</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V6WXImVudDHCLSO_" /></figure><h3>Typed vs Non-Typed Languages</h3><p>In programming, <strong>typed languages</strong> enforce rules around data types, dictating how variables and functions can interact with different types of data (e.g., strings, numbers). Typed languages ensure type safety, reducing bugs and making the code more predictable.</p><p><strong>Strongly Typed Languages</strong> like Java, C++, and Rust are strict about type assignments. Once a variable is declared with a specific type, it cannot hold values of a different type. For example, assigning a string to an integer variable will result in a compile-time error. This prevents many runtime errors but requires more careful type management.</p><p><strong>Loosely Typed Languages</strong> like JavaScript and Python, on the other hand, are more flexible. Variables can change types dynamically, and implicit conversions between types are common. This flexibility allows for faster development but can lead to harder-to-diagnose runtime errors.</p><h3>TypeScript Overview</h3><p><strong>TypeScript</strong> is a <strong>programming language developed and maintained by Microsoft</strong>. It is a <strong>strict syntactical superset of JavaScript</strong> and adds optional <strong>static typing</strong> to the language. This means that TypeScript builds on JavaScript by introducing types, allowing developers to catch potential errors early during the development process.Key benefits of TypeScript:</p><ol><li><strong>Static Typing</strong>: Detects type-related errors at compile time, reducing runtime bugs.</li><li><strong>Improved Tooling</strong>: Provides better editor support with features like auto-completion, code navigation, and refactoring.</li><li><strong>Optional Typing</strong>: Types are optional, so developers can gradually adopt TypeScript into existing JavaScript codebases.</li></ol><pre>function greet(name: string): string {<br>  return &quot;Hello, &quot; + name;<br>}<br><br>const result = greet(&quot;World&quot;);  // Works fine<br>const result = greet(123);      // Type error: 123 is not a string</pre><h3>How Does TypeScript Run?</h3><p>TypeScript <strong>does not run directly in your browser</strong> or Node.js. JavaScript is the only language that browsers and Node.js can execute. TypeScript code needs to be <strong>compiled</strong> (or “transpiled”) into JavaScript before it can run in the browser or a JavaScript runtime.</p><p>The process works as follows:</p><ol><li><strong>Write TypeScript code</strong>: You write .ts files containing TypeScript code.</li><li><strong>Compile to JavaScript</strong>: A TypeScript compiler converts the .ts files into .js files, with type-checking along the way. If there are type errors, the compilation fails.</li><li><strong>Run the JavaScript code</strong>: The resulting JavaScript code is what actually runs in the browser or Node.js environment.</li></ol><h3>TypeScript Compiler</h3><p>The official TypeScript compiler is called <strong>tsc</strong>. It is used to convert TypeScript files into JavaScript. However, other fast compilers and transpilers are often used for this process in modern development environments.</p><p>Some popular TypeScript compilers/transpilers are:</p><ul><li><strong>esbuild</strong>: Known for its extremely fast compilation speed.</li><li><strong>swc</strong>: A Rust-based compiler, offering both speed and efficient type-checking.</li></ul><p>Using these tools, TypeScript allows for improved safety, while still compiling down to efficient and widely-supported JavaScript that can run anywhere.</p><h3>Everyday Types in TypeScript</h3><p>When working with TypeScript, understanding basic types is essential for writing type-safe and predictable code. This article covers some of the most commonly used types in TypeScript: any, unknown, never, undefined, null, arrays, tuples, type inference, and the Record utility type.</p><h3>1. any</h3><p>The any type is the most flexible type in TypeScript. It can hold <strong>any value</strong> and bypasses type-checking altogether, effectively disabling TypeScript&#39;s static type system for that variable.</p><pre>let anything: any;<br>anything = 5;<br>anything = &quot;hello&quot;;  // No error</pre><p>However, overusing any can lead to errors as it removes type safety. It&#39;s typically better to use more specific types whenever possible.</p><h3>2. unknown</h3><p>The unknown type is similar to any, but it enforces type checking before using the value. It requires you to perform a type check or cast before you can work with it safely. This makes unknown a <strong>safer alternative to </strong><strong>any</strong>.</p><pre>let value: unknown;<br>value = &quot;Hello&quot;;<br><br>if (typeof value === &quot;string&quot;) {<br>  console.log(value.toUpperCase());  // Safe: value is checked to be a string<br>}</pre><p>With unknown, you cannot directly perform operations without ensuring its type, making it more type-safe than any.</p><h3>3. never</h3><p>The never type represents values that <strong>never occur</strong>. It&#39;s used primarily in functions that throw errors or have infinite loops, i.e., functions that never return. The never type signals that a function doesn’t successfully complete its execution, making it useful for marking unreachable code paths.</p><pre>function throwError(message: string): never {<br>  throw new Error(message);<br>}</pre><h3>4. undefined and null</h3><p>Both undefined and null are used to represent the absence of a value.</p><ul><li><strong>undefined</strong>: A variable that has been declared but not assigned a value.</li></ul><pre>let x: undefined;<br>x = undefined;  // Valid assignment</pre><ul><li><strong>null</strong>: Represents an explicitly empty or non-existent value.</li></ul><pre>let y: null;<br>y = null;  // Valid assignment</pre><p>In TypeScript, undefined and null are treated as distinct types, but you can enable more flexible behavior using the strictNullChecks flag in the compiler, which ensures stricter checks around these values.</p><h3>5. Arrays</h3><p>Arrays in TypeScript can be typed to ensure that they contain only elements of a specific type. There are two ways to define an array type:</p><ol><li><strong>Type[]</strong> syntax:</li></ol><pre>let numbers: number[] = [1, 2, 3];</pre><p><strong>2. Array&lt;Type&gt;</strong> syntax:</p><pre>let strings: Array&lt;string&gt; = [&quot;hello&quot;, &quot;world&quot;];</pre><p>Using these annotations ensures that the array only holds elements of the specified type, improving type safety.</p><h3>6. Tuples</h3><p>Tuples allow for fixed-length arrays where each element has a specific type. Unlike regular arrays where all elements share the same type, tuples can mix and match different types for each position, making them useful in structured data. Each element in the tuple is tied to its index, ensuring stricter data structures.</p><pre>let user: [string, number, boolean];<br>user = [&quot;Alice&quot;, 30, true];  // Valid tuple<br><br>// user = [30, &quot;Alice&quot;, true];  // Error: Order and types don&#39;t match</pre><h3>7. Object Types</h3><p>In TypeScript, you can define types for objects with specific key-value pairs. Object types allow you to describe the shape and structure of an object, specifying the types of the properties. This approach guarantees that any object adhering to the User type must have the specified keys and types.</p><pre>interface User {<br>  name: string;<br>  age: number;<br>  isAdmin: boolean;<br>}<br><br>const user: User = {<br>  name: &quot;John&quot;,<br>  age: 25,<br>  isAdmin: false,<br>};</pre><h3>8. Index Signatures</h3><p>Index signatures allow you to define dynamic object keys with a consistent value type. This is useful when you don’t know the exact keys ahead of time but know the type of the values those keys will hold.</p><pre>interface StringMap {<br>  [key: string]: string;<br>}<br><br>const myDictionary: StringMap = {<br>  name: &quot;Alice&quot;,<br>  country: &quot;USA&quot;,<br>  city: &quot;New York&quot;,<br>};</pre><p>In this example, the index signature [key: string] ensures that all properties on myDictionary will have string values.</p><h3>9. Enums</h3><p>Enums allow you to define a set of named constants. They are especially useful for representing fixed sets of values, such as days of the week, user roles, or status codes.</p><pre>enum Status {<br>  Active,<br>  Inactive,<br>  Pending,<br>}<br><br>let currentStatus: Status = Status.Active;</pre><p>Enums can also be numeric (as shown) or string-based. They provide a clear way to manage predefined options in your code.</p><pre>enum Role {<br>  Admin = &quot;Admin&quot;,<br>  User = &quot;User&quot;,<br>  Guest = &quot;Guest&quot;,<br>}<br><br>let userRole: Role = Role.Admin;</pre><h3>10. Type Aliases</h3><p>Type aliases in TypeScript allow you to create custom type names, making your code cleaner and more readable. Aliases can represent any type, from primitives to complex types like unions or intersections.</p><pre>type ID = string | number;<br><br>let userId: ID;<br>userId = &quot;abc123&quot;;  // Valid<br>userId = 123;       // Valid</pre><h3>11. Interfaces</h3><p>Interfaces in TypeScript define the structure of an object, similar to object types, but they are more powerful due to features like inheritance and extending other interfaces. Interfaces allow for <strong>extends</strong> and <strong>implements</strong>, enabling more flexibility and reuse in complex systems.</p><pre>interface Person {<br>  name: string;<br>  age: number;<br>}<br><br>interface Employee extends Person {<br>  position: string;<br>}<br><br>const employee: Employee = {<br>  name: &quot;Alice&quot;,<br>  age: 30,<br>  position: &quot;Manager&quot;,<br>};</pre><p>These types and constructs form the foundation of type safety and structure in TypeScript, making it a powerful tool for writing reliable, scalable code. In the next part, more advanced utility types will be discussed.</p><p>If you like the article then follow me on socials ,<br><strong><em>linkedin </em></strong>: <a href="https://www.linkedin.com/in/dilli-raj-timalsina/">https://www.linkedin.com/in/dilli-raj-timalsina/</a><br><strong><em>twitter </em></strong>: <a href="https://twitter.com/dillirajtweets">https://twitter.com/dillirajtweets</a><br><strong><em>github </em></strong>: <a href="https://github.com/Dilli-Raj-Timalsina">https://github.com/Dilli-Raj-Timalsina</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c3302345eb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced SQL (case, null functions) : Part 1.]]></title>
            <link>https://medium.com/@dillirajtimalsina354/advanced-sql-case-null-functions-part-1-de8c97cf7996?source=rss-8801448700cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/de8c97cf7996</guid>
            <category><![CDATA[sql-functions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[advanced-analytics]]></category>
            <dc:creator><![CDATA[Dillirajtimalsina]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 05:01:17 GMT</pubDate>
            <atom:updated>2024-09-25T05:01:17.871Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced SQL (case, null functions) : Part 1.</h3><p>This is a part 1 of many<strong> ( <em>Advanced SQL)</em></strong><em> concepts in which we will cover </em>the CASE expression and NULLIF/COALESCE functions in SQL, which are both powerful tools for handling conditional logic and null values in queries.</p><h3>1. CASE Expression</h3><p>The CASE expression allows you to add conditional logic to your SQL queries. It&#39;s similar to an IF...ELSE structure in programming languages.</p><pre>SELECT <br>    column1,<br>    CASE <br>        WHEN condition1 THEN result1<br>        WHEN condition2 THEN result2<br>        ELSE default_result<br>    END AS alias_name<br>FROM <br>    table_name;</pre><h4>Example:</h4><p>Consider a students table with columns: id, name, and score. We want to categorize each student&#39;s performance:</p><pre>SELECT<br>    id,<br>    name,<br>    score,<br>    CASE<br>        WHEN score &gt;= 90 THEN &#39;Excellent&#39;<br>        WHEN score &gt;= 75 THEN &#39;Good&#39;<br>        WHEN score &gt;= 50 THEN &#39;Average&#39;<br>        ELSE &#39;Needs Improvement&#39;<br>    END AS performance<br>FROM<br>    students;</pre><p>This query assigns a performance level to each student based on their score.</p><h4>Edge Cases:</h4><ol><li>Missing ELSE Clause: If none of the conditions are met and there’s no ELSE, the result is NULL.</li><li>Data Type Consistency: Ensure all THEN and ELSE parts return the same data type.</li></ol><h3>2. Handeling Null with Functions :</h3><p>NULLs are often tricky in SQL, and these functions can help manage them effectively.</p><h4>NULLIF Function:</h4><p>NULLIF returns NULL if two expressions are equal; otherwise, it returns the first expression.</p><p>Basic Syntax:</p><pre>SELECT NULLIF(expression1, expression2) AS result;</pre><p>Example:</p><p>Check if discount_price equals original_price, and return NULL if true:</p><pre>SELECT <br>    product_name,<br>    NULLIF(discount_price, original_price) AS effective_discount<br>FROM <br>    products;</pre><p>If discount_price is equal to original_price, effective_discount will be NULL.</p><h4>COALESCE Function:</h4><p>COALESCE returns the first non-NULL value in a list of expressions.</p><p>Basic Syntax:</p><pre>SELECT COALESCE(expression1, expression2, ..., expressionN) AS result;</pre><p>Example:</p><p>Select the first available contact detail (phone, email, or address):</p><pre>SELECT <br>    name,<br>    COALESCE(phone, email, address, &#39;No Contact Info&#39;) AS contact_info<br>FROM <br>    customers;</pre><p>This query checks for the first non-NULL value among phone, email, and address. If all are NULL, it defaults to &#39;No Contact Info&#39;.</p><h3>Conclusion</h3><p>The CASE expression and functions like NULLIF and COALESCE are indispensable in SQL for crafting flexible, robust queries. They enable handling of conditional logic and null scenarios with elegance and precision. In future parts, we&#39;ll explore more advanced SQL techniques to enhance your data querying capabilities.</p><p>If you like the article then follow me on socials ,<br><strong><em>linkedin </em></strong>: <a href="https://www.linkedin.com/in/dilli-raj-timalsina/">https://www.linkedin.com/in/dilli-raj-timalsina/</a><br><strong><em>twitter </em></strong>: <a href="https://twitter.com/dillirajtweets">https://twitter.com/dillirajtweets</a><br><strong><em>github </em></strong>: <a href="https://github.com/Dilli-Raj-Timalsina">https://github.com/Dilli-Raj-Timalsina</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de8c97cf7996" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>