<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Omari</title>
    <description>The latest articles on Forem by Omari (@marileon).</description>
    <link>https://forem.com/marileon</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1265923%2F372cb050-deec-44ad-8907-55c842308fc1.jpeg</url>
      <title>Forem: Omari</title>
      <link>https://forem.com/marileon</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/marileon"/>
    <language>en</language>
    <item>
      <title>ECMAScript vs JavaScript vs TypeScript</title>
      <dc:creator>Omari</dc:creator>
      <pubDate>Tue, 05 Mar 2024 10:43:23 +0000</pubDate>
      <link>https://forem.com/marileon/ecmascript-vs-javascript-vs-typescript-42pi</link>
      <guid>https://forem.com/marileon/ecmascript-vs-javascript-vs-typescript-42pi</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--D1b9yL7i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/0%2ACijLZfmvdm3aP4FK" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--D1b9yL7i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/0%2ACijLZfmvdm3aP4FK" alt="" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;While you’re reading about JavaScript and TypeScript online, you might come across references to some mystical third language — ECMAScript. Think of terms like ES6 or ES2016. ECMAScript is a specification that defines the language features of JavaScript, and therefore TypeScript. Let’s delve into the details.&lt;/p&gt;

&lt;h3&gt;
  
  
  JavaScript.
&lt;/h3&gt;

&lt;p&gt;So if you’re here you probably already know what JavaScript is, but just in case let’s go through it. JavaScript is a high-level weakly-typed programming language, originally just used for building dynamic web pages, but now becoming increasingly common for general programming and back-end servers. It’s powering 98.8% of websites, so it’s quite popular.&lt;/p&gt;

&lt;h3&gt;
  
  
  ECMAScript.
&lt;/h3&gt;

&lt;p&gt;ECMAScript is the standard that JavaScript implements. JavaScript did previously have a few siblings that also implemented ECMAScript, like ActionScript and JScript, but JavaScript is pretty much the only one that survived, which is why you’ll see JavaScript and ECMAScript used pretty interchangeably. The name comes from Ecma International, a nonprofit standards organisation for ICT.&lt;/p&gt;

&lt;p&gt;ECMAScript defines the language features and syntax, but not things like I/O.&lt;/p&gt;

&lt;p&gt;Things ECMAScript does define:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Array methods&lt;/li&gt;
&lt;li&gt;Syntax&lt;/li&gt;
&lt;li&gt;Operators&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Things ECMAScript doesn’t define:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;File system handling&lt;/li&gt;
&lt;li&gt;DOM manipulation&lt;/li&gt;
&lt;li&gt;Networking&lt;/li&gt;
&lt;li&gt;Graphics&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Since 2015, a new major version of ECMAScript has been published every June. This starts with ECMAScript 2015, or ES2015. You might also see it referred to as ES6, since it’s the 6th major edition of ECMAScript.&lt;/p&gt;

&lt;p&gt;You’ll see ES6 mentioned a lot online as it was a significant improvement, adding features like the “let” and “const” keywords, arrow functions, maps and sets, and many more.&lt;/p&gt;

&lt;p&gt;So every year a new ECMAScript edition is approved and published by the ECMA General Assembly. Before ES6 there was a new specification more sporadically, every few years. They were referred to by edition, e.g. ES4 or ES5. Following ES6 each version is referred to by the year it was published, e.g. ES6 is ES2015. There’s also ESNext, which refers to whatever the next version is.&lt;/p&gt;

&lt;p&gt;ECMAScript features have to go through a 4 stage application process:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Stage 0 is a new proposal&lt;/li&gt;
&lt;li&gt;Stage 1 is a proposal under consideration&lt;/li&gt;
&lt;li&gt;Stage 2 is where a solution/design gets drafted for a proposal&lt;/li&gt;
&lt;li&gt;Stage 3 is where a proposal feature has been tested, and is recommended to be implemented. There’s not likely to be any major changes, but there may still be some minor changes from feedback&lt;/li&gt;
&lt;li&gt;Stage 4 is the final stage, and means a feature is complete and ready to be included in the standard&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is all public, by the way. You can follow along with ECMAScript proposals and meeting notes &lt;a href="https://github.com/tc39"&gt;here&lt;/a&gt; if you want to take a look at new potential JavaScript features.&lt;/p&gt;

&lt;h3&gt;
  
  
  TypeScript.
&lt;/h3&gt;

&lt;p&gt;TypeScript is a programming language developed by Microsoft to add static typing, and optional type annotations to JavaScript. It’s a superset of JavaScript, meaning all JavaScript is valid TypeScript, but not all TypeScript is valid JavaScript.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Valid JavaScript, and valid TypeScript but it will complain about the lack of types
function add(a, b) {
    return a + b;
}
//Valid TypeScript with types, now invalid JavaScript
function add(a: number, b: number): number {
    return a + b;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Conclusion.
&lt;/h3&gt;

&lt;p&gt;So to sum everything up:&lt;/p&gt;

&lt;p&gt;JavaScript is based on a standard called ECMAScript. Technically JavaScript isn’t ECMAScript, but it’s the only version of it that still matters.&lt;br&gt;&lt;br&gt;
 ECMAScript decides the baseline features JavaScript implements.&lt;br&gt;&lt;br&gt;
 TypeScript is a superset of JavaScript that adds static typing and type annotations to JavaScript.&lt;/p&gt;

&lt;p&gt;That’s everything! Thanks for reading — if you liked this article, feel free to share this article, or follow me on &lt;a href="https://twitter.com/marile0n"&gt;Twitter.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://www.omarileon.me/blog/typescript-vs-ecmascript"&gt;&lt;em&gt;https://www.omarileon.me&lt;/em&gt;&lt;/a&gt; &lt;em&gt;on March 5, 2024.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascripttips</category>
      <category>javascript</category>
      <category>typescript</category>
      <category>programming</category>
    </item>
    <item>
      <title>Are TypeScript enums Still Bad?</title>
      <dc:creator>Omari</dc:creator>
      <pubDate>Wed, 21 Feb 2024 14:42:09 +0000</pubDate>
      <link>https://forem.com/marileon/are-typescript-enums-still-bad-35ab</link>
      <guid>https://forem.com/marileon/are-typescript-enums-still-bad-35ab</guid>
      <description>&lt;p&gt;If you search for TypeScript enums online, you’ll see they get a lot of hate. Have there been any improvements to enums over time, or are they still generally frowned upon?&lt;/p&gt;

</description>
      <category>discuss</category>
      <category>typescript</category>
      <category>javascript</category>
      <category>webdev</category>
    </item>
    <item>
      <title>A Quick Guide to Clamping Numbers in JavaScript</title>
      <dc:creator>Omari</dc:creator>
      <pubDate>Thu, 08 Feb 2024 02:32:12 +0000</pubDate>
      <link>https://forem.com/marileon/a-quick-guide-to-clamping-numbers-in-javascript-4dca</link>
      <guid>https://forem.com/marileon/a-quick-guide-to-clamping-numbers-in-javascript-4dca</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JZFlkxeO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/0%2AFCHT63t_rFys4Fvx" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JZFlkxeO--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/0%2AFCHT63t_rFys4Fvx" alt="" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In JavaScript, there’s “Math.min()”, “Math.max()”, but unfortunately no Math.clamp(). There’s but it’s currently in the draft stages. This is fine — it’s very easy to implement clamp, and in this article, I’ll talk through doing just that.&lt;/p&gt;

&lt;h3&gt;
  
  
  A Quick Way
&lt;/h3&gt;

&lt;p&gt;You can use the following function to clamp a number between a minimum and maximum value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function clamp(num: number, lower: number, upper: number) {
    return Math.min(Math.max(num, lower), upper);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why does this work? Let’s think it through. At first, our number is any valid JavaScript number, anything in the range &lt;strong&gt;-Number.MAX_VALUE &amp;lt;= num &amp;lt;= Number.MAX_VALUE&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Then we have:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Math.max(num, lower);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So now our range gets updated to whatever the larger value is out of “lower” and “num”. Our range is now: &lt;strong&gt;lower &amp;lt;= num &amp;lt;= Number.MAX_VALUE.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I’m sure you can see where this is going — let’s break our code up:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const lowerBound = Math.max(num, lower);
const result = Math.min(num, upper);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Just like before but reversed. Our result is the lower of num or upper, so we can update our range to: &lt;strong&gt;lower &amp;lt;= num &amp;lt;= upper.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;And just like that, our number is clamped! If it’s lower than the lower bound, we pick the lower bound. If it’s higher than the upper bound, we pick the upper bound. Otherwise, we pick the number.&lt;/p&gt;

&lt;h3&gt;
  
  
  Lodash
&lt;/h3&gt;

&lt;p&gt;Lodash is a JavaScript utility library. You can install it with one of these commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i lodash 
pnpm add lodash 
yarn add lodash
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And it works exactly the same as our function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { clamp } from 'lodash'; 
clamp(number, lower, upper);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Short and simple! If you’re not familiar with Lodash, it can be quite handy if you’re looking for any functions not native to JavaScript. Check it out .&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;So there’s two ways of getting the clamp math function into your JavaScript code. Which one should you use? Personally, I think since it’s such a small function, you should probably just implement this one yourself if you need it. If you’re already using Lodash though, then you may as well use their built-in function. Thanks for reading! If you liked this article, why not follow me on &lt;a href="https://twitter.com/marile0n"&gt;Twitter&lt;/a&gt;?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://www.omarileon.me/blog/javascript-clamp"&gt;&lt;em&gt;https://www.omarileon.me&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>programming</category>
      <category>typescript</category>
      <category>coding</category>
      <category>javascript</category>
    </item>
    <item>
      <title>The Best Way to Handle Promises in React</title>
      <dc:creator>Omari</dc:creator>
      <pubDate>Tue, 06 Feb 2024 14:59:52 +0000</pubDate>
      <link>https://forem.com/marileon/the-best-way-to-handle-promises-in-react-5399</link>
      <guid>https://forem.com/marileon/the-best-way-to-handle-promises-in-react-5399</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2A_JnQ_TDZhxvD00TI" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2A_JnQ_TDZhxvD00TI"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Promises are a great feature in JavaScript, used for data fetching or any asynchronous code. At first, it can be a struggle to figure out the best way to integrate Promises into the React ecosystem, so in this article we’ll go through a few options of how to do exactly that.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a Promise?
&lt;/h3&gt;

&lt;p&gt;Promises allow you to perform asynchronous operations in JavaScript. To construct a Promise from scratch, you can use the Promise constructor. This takes a function which takes two parameters: “resolve”, a function to call when the operation completes, and “reject”, a function to call if the operation fails. You then have to call one of these functions when your operation completes.&lt;/p&gt;

&lt;p&gt;Promises are a way of performing asynchronous operations in JavaScript. They’re a way of saying “I don’t have the value of this now, but I will at some point in the future”.&lt;br&gt;&lt;br&gt;
 You can construct a promise from scratch using the Promise constructor. It takes two functions as parameters: “resolve”, a function to call when the operation completes successfully, and “reject”, a function to call if the operation fails. You then have to call one of these functions when your operation completes, called “settling” a promise.&lt;/p&gt;

&lt;p&gt;JavaScript includes two ways of getting the result of a promise. Let’s take a look at both.&lt;/p&gt;
&lt;h3&gt;
  
  
  .then()
&lt;/h3&gt;

&lt;p&gt;The first is “.then()”, a method on Promises which accepts a callback function to run when the promise resolves. Here’s what that looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myPromise = new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; {
        resolve('follow @marile0n');
    }, 1000); //1000ms = 1s
});
myPromise.then((val) =&amp;gt; {
    console.log(val);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;.then() returns another promise, which lets you chain together actions:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const healthyItems = ['apple', 'banana', 'carrot'];
function fetchShoppingBasket(): Promise&amp;lt;string[]&amp;gt; {
    //...
}
function countHealthyItems() {
    fetchShoppingBasket()
        .then((items) =&amp;gt; items.filter((item) =&amp;gt; healthyItems.includes(item)))
        .then((healthyItems) =&amp;gt; healthyItems.length);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This works even if the next function you call in .then() isn’t asynchronous.&lt;/p&gt;

&lt;p&gt;There are also two other related methods, .catch() and .finally(). .catch() is used for catching errors, and .finally() runs after a promise is settled, i.e. whether it completes successfully, or throws an error:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;myPromise
    .then(() =&amp;gt; console.log('Ill run first'))
    .then(() =&amp;gt; console.log('Ill run second'))
    .then(() =&amp;gt; {
        throw new Error('Whoops!');
    })
    .catch((e) =&amp;gt; console.log('Ill run after an error:', e))
    .finally(() =&amp;gt; console.log('Ill run last'));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2Ag4fPyLeL3SziMGSW.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2Ag4fPyLeL3SziMGSW.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Async/Await
&lt;/h3&gt;

&lt;p&gt;The other way of handling promises in React is the async/await syntax. You can “await” a function to synchronously wait for the promise to settle:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myPromise = new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; {
        resolve('follow @marile0n');
    }, 1000); //1000ms = 1s
});
const result = await myPromise;
console.log(result);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This lets you use a regular try…catch statement to handle errors. Here’s the above promise, converted to async/await&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {
    await myPromise;
    console.log('Ill run first');
    console.log('Ill run second');
    throw new Error('Whoops!');
} catch (e) {
    console.log('Ill run after an error:', e);
} finally {
    console.log('Ill run last');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you use await in a function, it must be marked as asynchronous with the “async” keyword:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async function myAsyncFunction() {
    //...
}
const myLambdaAsyncFunction = async () =&amp;gt; {
    //...
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, onto the React part.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Plain Way
&lt;/h3&gt;

&lt;p&gt;You can handle a Promise in React using useEffect to call the Promise, and a useState to store the result. It’s also useful to set up some other values to track the state of the asynchronous action.&lt;/p&gt;

&lt;p&gt;We’ll start off with our Promise. We’ll be using the handy — A great API for retrieving pictures of cats. Here’s the code for retrieving a cat:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type CatResponse = { _id: string };
async function getCat() {
    return axios
        .get&amp;lt;CatResponse&amp;gt;('https://cataas.com/cat?json=true')
        .then((res) =&amp;gt; {
            console.log(res.data);
            return 'https://cataas.com/cat/' + res.data._id;
        });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let’s build that together in a React component. We’ll set up some state hooks:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [cat, setCat] = useState('');
const [status, setStatus] = useState&amp;lt;'pending' | 'success' | 'error'&amp;gt;(
    'pending'
);
const [error, setError] = useState&amp;lt;Error&amp;gt;();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three state values — one to track the returned cat, one to track the state of the promise, and one to store an error if we get one.&lt;/p&gt;

&lt;p&gt;Then we have our useEffect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
    setStatus('pending');
    getCat()
        .then((cat) =&amp;gt; {
            setCat(cat);
            setStatus('success');
        })
        .catch((e) =&amp;gt; {
            console.log(e);
            setStatus('error');
            setError(e);
        });
}, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To use the value of our promise, we can use a &lt;strong&gt;&lt;em&gt;useEffect()&lt;/em&gt;&lt;/strong&gt; hook with an empty dependency array. The function will get called the first time the component mounts, which changes our state and performs our API call. Then when the API call is done, our state values get updated, or if there’s an error, that gets stored.&lt;/p&gt;

&lt;p&gt;Or we can rewrite this using async/await:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
    setStatus('pending');
    try {
        const cat = await getCat(); //'await' expressions are only allowed within async functions and at the top levels of modules.
        setCat(cat);
        setStatus('success');
    } catch (e) {
        console.log(e);
        setStatus('error');
        setError(e as Error);
    }
}, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Oh wait, but since we’re using await, we need to mark our function as async:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Effect callbacks are synchronous to prevent race conditions.
useEffect(async () =&amp;gt; {
    setStatus('pending');
    try {
        const cat = await getCat();
        setCat(cat);
        setStatus('success');
    } catch (e) {
        console.log(e);
        setStatus('error');
        setError(e as Error);
    }
}, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we run into another error — the useEffect function cannot be asynchronous.&lt;/p&gt;

&lt;p&gt;How do we solve this? Move the code to an async function, and then call that function from your useEffect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
    async function fetchCat() {
        setStatus('pending');
        try {
            const cat = await getCat();
            //'await' expressions are only allowed within async functions and at the top levels of modules.
            setCat(cat);
            setStatus('success');
        } catch (e) {
            console.log(e);
            setStatus('error');
            setError(e as Error);
        }
    }
    fetchCat();
}, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we can put this together with some JSX to display the results:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Cat() {
    const [cat, setCat] = useState('');
    const [status, setStatus] = useState&amp;lt;'pending' | 'success' | 'error'&amp;gt;(
        'pending'
    );
    const [error, setError] = useState&amp;lt;Error&amp;gt;();
    useEffect(() =&amp;gt; {
        async function fetchCat() {
            setStatus('pending');
            try {
                const cat = await getCat(); //'await' expressions are only allowed within async functions and at the top levels of modules.
                setCat(cat);
                setStatus('success');
            } catch (e) {
                console.log(e);
                setStatus('error');
                setError(e as Error);
            }
        }
        fetchCat();
    }, []);
    if (status === 'pending') return &amp;lt;h1&amp;gt;Loading...&amp;lt;/h1&amp;gt;;
    if (status === 'error') return &amp;lt;h1&amp;gt;Error! {error?.message}&amp;lt;/h1&amp;gt;;
    return (
        &amp;lt;div className="relative h-full w-96"&amp;gt;
            {' '}
            &amp;lt;Image
                src={cat}
                alt="Cat"
                fill
                className="h-full w-full object-contain"
            /&amp;gt;{' '}
        &amp;lt;/div&amp;gt;
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And here’s what it all looks like:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2AwgQ_0ncyIVQ5xpzI.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2AwgQ_0ncyIVQ5xpzI.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So pretty straightforward, but a little verbose, even with just the basic functionality we’ve implemented here.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Better Way
&lt;/h3&gt;

&lt;p&gt;If you look online, you’ll see a lot of negative sentiment around using useEffect to handle promises. The main reason why is that it’s preferable to use existing libraries, rather than re-inventing the wheel. The most popular library for handling asynchronous promises in React is TanStack Query (formerly known as React Query). Let’s take a look at it by recreating our previous example with TanStack Query.&lt;/p&gt;

&lt;p&gt;First you’ll need to install TanStack Query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @tanstack/react-query
yarn add @tanstack/react-query 
pnpm add @tanstack/react-query
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we need to set up a QueryClient and a provider for our components to be able to access the client. I’m using the app directory in Next.js, so here’s how I’ve done it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//Proiders.tsx
('use client');
import { QueryClientProvider, QueryClient } from '@tanstack/react-query';
import { WithChildrenProps } from '@/types';
const queryClient = new QueryClient();
export function Providers({ children }: WithChildrenProps) {
    return (
        &amp;lt;QueryClientProvider client={queryClient}&amp;gt;
            {' '}
            {children}{' '}
        &amp;lt;/QueryClientProvider&amp;gt;
    );
}

//layout.tsx
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
import { Providers } from './providers';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
    title: 'Create Next App',
    description: 'Generated by create next app',
};
export default function RootLayout({
    children,
}: Readonly&amp;lt;{ children: React.ReactNode }&amp;gt;) {
    return (
        &amp;lt;html lang="en"&amp;gt;
            {' '}
            &amp;lt;body className={inter.className}&amp;gt;
                {' '}
                &amp;lt;Providers&amp;gt;{children}&amp;lt;/Providers&amp;gt;{' '}
            &amp;lt;/body&amp;gt;{' '}
        &amp;lt;/html&amp;gt;
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then, essentially all the extra logic we wrote before can be swapped out for React Query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function TanCatQuery() {
    const {
        data: cat,
        isPending,
        error,
    } = useQuery({ queryKey: ['cat'], queryFn: () =&amp;gt; getCat() });
    if (isPending) return &amp;lt;h1&amp;gt;Loading...&amp;lt;/h1&amp;gt;;
    if (error) return &amp;lt;h1&amp;gt;Error! {error.message}&amp;lt;/h1&amp;gt;;
    return (
        &amp;lt;div className="relative h-full w-96"&amp;gt;
            {' '}
            &amp;lt;Image
                src={cat}
                alt="Cat"
                fill
                className="h-full w-full object-contain"
            /&amp;gt;{' '}
        &amp;lt;/div&amp;gt;
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The useQuery hook accepts an asynchronous function to call, as well as a key to be used when caching queries, and in return we get all the logic we previously had. React Query also has a lot of other benefits such as built-in caching, reduping requests, automatic retrying, etc.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;So which one should you use? If you’re performing your promises outside of a React component, you can skip React Query, otherwise the choice is yours. Personally, I tend to reach for React Query straight away, as it greatly simplifies asynchronous code in React, but it’s all up to you — pick the best fit for your app. Check out the full code &lt;a href="https://github.com/lofi-marz/example-react-promises" rel="noopener noreferrer"&gt;here&lt;/a&gt; and thanks for reading!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="http://omarileon.me/blog/react-promises" rel="noopener noreferrer"&gt;&lt;em&gt;https://www.omarileon.me&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Non-Null Assertions: The Forbidden Typescript Operator</title>
      <dc:creator>Omari</dc:creator>
      <pubDate>Fri, 02 Feb 2024 11:47:51 +0000</pubDate>
      <link>https://forem.com/marileon/non-null-assertions-the-forbidden-typescript-operator-1e5c</link>
      <guid>https://forem.com/marileon/non-null-assertions-the-forbidden-typescript-operator-1e5c</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F1%2AketRIhBsLZt2FocGcawu6Q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F1%2AketRIhBsLZt2FocGcawu6Q.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The non-null assertion operator, or that weird exclamation mark you might be seeing in TypeScript is an operator that tells TypeScript that a value won’t be null or undefined. In a technical sense, it eliminates null and undefined from the type of your variable. In this article I’ll cover the operator, how to use it, and why maybe not to.&lt;/p&gt;

&lt;p&gt;Here’s what it looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getName(): string | null {
    // ...
}
function greet(name: string) {
    console.log(`Hi ${name}`);
}
const myName = getName(); //string | null
greet(myName); //Argument of type 'string | null' is not assignable to parameter of type 'string'. 
//Type 'null' is not assignable to type 'string'. 
greet(myName!) //✅t
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Add an exclamation mark onto the end of a variable, and the result is that variable with any null or undefined eliminated from its type.&lt;/p&gt;

&lt;h3&gt;
  
  
  Should you use it?
&lt;/h3&gt;

&lt;p&gt;You should be aware of the fact that the operator isn’t doing anything to the variable itself, just forcing TypeScript to believe it will exist. Let’s take our previous example, and fill in our function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getName() {
    return Math.random() &amp;gt; 0.5 ? 'Omari' : null;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;No need to add a return type anymore, TypeScript knows the function will always return a string or null.&lt;/p&gt;

&lt;p&gt;The rest of the code still works:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function greet(name: string) {
    console.log(`Hi ${name}`);
}
const myName = getName(); //string | null 
greet(myName!); //✅
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even though we know something is wrong — “myName” will be null about half the time.&lt;/p&gt;

&lt;p&gt;This is a simplified example, but the point is that you should be aware of why TypeScript thinks your variable might be null or undefined in the first place, and whether it’s worth risking the chance that it is. In this case, our code will still run, we’ll just get “Hi null”, so not too bad, but there are some alternatives.&lt;/p&gt;

&lt;h3&gt;
  
  
  What to use instead
&lt;/h3&gt;

&lt;p&gt;The easiest solution to handle if your variable is null or undefined is to use type guards. Null and undefined are &lt;a href="https://www.omarileon.me/blog/typescript-primitive-conversion" rel="noopener noreferrer"&gt;falsy&lt;/a&gt;, which makes it easy to check in an if statement:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (myName) greet(myName);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will include all falsy values, for example the empty string. In this case that’s helpful — we probably wouldn’t want to greet an empty name either, but you can also explicitly check for null or undefined with equality:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (myName !== null) greet(myName);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Another way to check for null or undefined is to use the &lt;a href="https://www.omarileon.me/blog/typescript-double-question-mark" rel="noopener noreferrer"&gt;nullish coalescing&lt;/a&gt; operator (??), — introduced in TypeScript 3.7. This operator returns the left-hand side of the expression if it’s not null or undefined, and the right-hand side otherwise. It’s useful for giving variables default values in the case that they are null or undefined:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myName = getName() ?? 'Omari'; //string | null greet(myName);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For not a lot more code, we’re back in alignment with TypeScript.&lt;/p&gt;

&lt;h3&gt;
  
  
  When might you use it?
&lt;/h3&gt;

&lt;p&gt;One case I have seen the non-null assertion operator used is maps. Imagine if we wanted to use a map to count how many times we’ve greeted someone:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function greetWithCount(name: string) {
    greet(name);
    if (greetings.has(name)) {
        const count = greetings.get(name);
        //const count: number | undefined
        greetings.set(name, count + 1);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You might be able to safely assume that inside the if statement, “.get()” should always return a value, since we’ve checked if that key has an entry. .get() always returns the type union “type | undefined” though. In this case, a quick non-null assertion is an easy solution. Again you could just check if “count” is undefined, but assuming the value exists isn’t the worst assumption in this case.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Thanks for reading! Hopefully, this article was a good introduction to that mysterious exclamation mark you’ve been seeing in TypeScript. Personally, I nearly always prefer handling null or undefined in other ways than the non-null assertion operator, but just like everything in coding, the choice is up to you!&lt;/p&gt;

&lt;p&gt;Hey, I’m Omari! I’m a full-stack developer from the UK. I’m currently looking for graduate and freelance software engineering roles, so if you liked this article, &lt;a href="https://omarileon.me/blog" rel="noopener noreferrer"&gt;check out my website&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="http://omarileon.me/blog/typescript-non-null-assertion" rel="noopener noreferrer"&gt;&lt;em&gt;https://www.omarileon.me&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>webdev</category>
      <category>coding</category>
    </item>
    <item>
      <title>A Comprehensive Guide to Converting Between Strings, Booleans and Numbers in Typescript</title>
      <dc:creator>Omari</dc:creator>
      <pubDate>Thu, 01 Feb 2024 13:13:44 +0000</pubDate>
      <link>https://forem.com/marileon/a-comprehensive-guide-to-converting-between-strings-booleans-and-numbers-in-typescript-gl8</link>
      <guid>https://forem.com/marileon/a-comprehensive-guide-to-converting-between-strings-booleans-and-numbers-in-typescript-gl8</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2AlkN5sQWcVuJmmX2e" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2AlkN5sQWcVuJmmX2e"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With TypeScript, comes types. Things are stricter than the implicit conversion you’ll see in JavaScript. This means you’ll need to know how to safely convert between types. In this article, I’ll cover options for converting between the three primitive types you’re likely to be converting between the most often — strings, numbers and booleans.&lt;/p&gt;

&lt;h3&gt;
  
  
  A Quick Note on Truthiness
&lt;/h3&gt;

&lt;p&gt;One important thing to discuss here is what it means to convert from something to a boolean. Converting a number to a boolean for example, if we say 0 is false and 1 is true, that makes sense right? But those aren’t the only numbers — what about 3 — true or false? Or -1, true or false? TypeScript, and JavaScript handle this with truthiness. A truthy value is anything that is considered true when treated as a boolean. It’s easier to go through the list of values that are falsy, which are:&lt;/p&gt;

&lt;p&gt;Everything else is truthy.&lt;/p&gt;

&lt;p&gt;So when converting values to boolean, it’s important to make a distinction between whether you want whatever your definition of true and false are for your context, and native TypeScript/JavaScript truthiness.&lt;/p&gt;

&lt;h3&gt;
  
  
  Strings
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Strings to Numbers
&lt;/h3&gt;

&lt;p&gt;There are two main ways to convert strings to numbers in TypeScript, parseFloat and the Number constructor.&lt;/p&gt;

&lt;h4&gt;
  
  
  Using parseFloat
&lt;/h4&gt;

&lt;p&gt;“parseFloat” is a built-in function that converts a string to a number. It scans the string from left to right until it encounters a character that cannot be converted to a number. It then returns the numeric value parsed up to that point.&lt;/p&gt;

&lt;p&gt;Here’s how you can use “parseFloat()” in TypeScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function stringToNumber(str: string) {
    return parseFloat(str);
}
console.log(stringToNumber('10')); //10 
console.log(stringToNumber('10 and 11')); //10 
console.log(stringToNumber('ten and 11')); //NaN 
console.log(stringToNumber('ten')); //NaN
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If we input a string that represents a number, we get out a number&lt;/li&gt;
&lt;li&gt;If we input a string that starts with a number, we get just that number&lt;/li&gt;
&lt;li&gt;If we input a string that doesn’t start with a number, we get NaN&lt;/li&gt;
&lt;li&gt;If we input a string with no number, we get NaN&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The NaN part is something to take note of. If you’re not familiar with NaN — it stands for Not A Number. It’s a special case that represents as you’d guess, anything that isn’t a number, for example 0/0, or the result of one of the number conversion functions failing.&lt;/p&gt;

&lt;p&gt;One important thing is that NaN === NaN is false, which means this is false:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(Number('ten') === Number('ten')); //false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So if your conversion silently fails and you compare the results, they will never be equal.&lt;/p&gt;

&lt;h4&gt;
  
  
  Using Number()
&lt;/h4&gt;

&lt;p&gt;The Number() constructor in TypeScript can be used to explicitly convert a string to a number. It tries to convert the argument passed to it into a number. If the argument cannot be converted into a valid number, it returns NaN. Let’s take a look:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function stringToNumber(str: string) {
    return Number(str);
}
console.log(stringToNumber('10')); //10
console.log(stringToNumber('10 and 11')); //NaN
console.log(stringToNumber('ten and 11')); //NaN
console.log(stringToNumber('ten')); //NaN
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pretty similar to “parseFloat()”.The big difference is in the second case. “parseFloat” will scan the string from left to right and find the number 10, whereas Number will see that the whole thing is not a valid number, so it will return NaN&lt;/p&gt;

&lt;h3&gt;
  
  
  Strings to Booleans
&lt;/h3&gt;

&lt;p&gt;There are a few ways to convert a string to a boolean, depending on what you want to consider true or false. The simplest way is just checking whether a string is truthy or not, which can be done with the Boolean() constructor:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function stringToBoolean(str: string) {
    return Boolean(str);
}

console.log(stringToBoolean('true')); //true
console.log(stringToBoolean('True')); //true 
console.log(stringToBoolean('false')); //true 
console.log(stringToBoolean('False')); //true 
console.log(stringToBoolean('')); //false 
console.log(stringToBoolean('Just a string')); //true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the string is truthy, the string returns true. This means any string that isn’t an empty string.&lt;/p&gt;

&lt;p&gt;This might not be useful depending on your use case. If you’re just checking if the string is empty then this works, but in other cases you might not want “false” or “False” to be considered truthy.&lt;/p&gt;

&lt;p&gt;The simplest way is just checking if the string is equal to “true”:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function stringToBoolean(str: string) {
    return str === 'true';
}
console.log(stringToBoolean('true')); //true
console.log(stringToBoolean('True')); //false
console.log(stringToBoolean('false')); //false
console.log(stringToBoolean('False')); //false
console.log(stringToBoolean('')); //false
console.log(stringToBoolean('Just a string')); //false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or for a case-insensitive version:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function stringToBoolean(str: string) {
    return str.toLowerCase() === 'true';
}
console.log(stringToBoolean('true')); //true
console.log(stringToBoolean('True')); //true
console.log(stringToBoolean('false')); //false
console.log(stringToBoolean('False')); //false
console.log(stringToBoolean('')); //false
console.log(stringToBoolean('Just a string')); //false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Numbers
&lt;/h3&gt;

&lt;h3&gt;
  
  
  Numbers to Strings
&lt;/h3&gt;

&lt;p&gt;The easiest way to convert a number to a string in TypeScript is through the .toString() method:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function numberToString(num: number) {
    return num.toString();
}
console.log(numberToString(42)); //"42"
console.log(numberToString(-1)); //"1"
console.log(numberToString(NaN)); //"NaN"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One neat feature of this function is that it lets you choose the base/radix of the string, which lets you do things like convert a number to binary:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function numberToString(num: number) {
    return num.toString(2);
}
console.log(numberToString(42)); //"101010"
console.log(numberToString(-10)); //"-1010"
console.log(numberToString(NaN)); //"NaN"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or convert a number to hexadecimal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function numberToString(num: number) {
    return num.toString(16);
}
console.log(numberToString(12648243)); //"c0ff33"
console.log(numberToString(-10)); //"-a"
console.log(numberToString(NaN)); //"NaN"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That covers converting a plain number to a plain string, but if you’re dealing with something like percentages there are ways to&lt;/p&gt;

&lt;h3&gt;
  
  
  Numbers to Booleans
&lt;/h3&gt;

&lt;p&gt;Like strings, the “Boolean()” constructor is the easiest way to convert a number to a boolean:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
function numberToBoolean(num: number) {
    return Boolean(num);
}
console.log(numberToBoolean(-1)); //true
console.log(numberToBoolean(0)); //false
console.log(numberToBoolean(1)); //true
console.log(numberToBoolean(NaN)); //false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Any numbers that aren’t NaN or 0 are truthy.&lt;/p&gt;

&lt;h3&gt;
  
  
  Booleans
&lt;/h3&gt;

&lt;p&gt;Booleans are a little more straightforward, since there are only two possible values, and they both convert easily to strings/numbers.&lt;/p&gt;

&lt;h3&gt;
  
  
  Booleans to Strings
&lt;/h3&gt;

&lt;p&gt;Booleans contain a handy “toString()” method for converting them to strings:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function booleanToString(bool: boolean) {
    return bool.toString();
}
console.log(booleanToString(true)); //"true"
console.log(booleanToString(false)); //"false"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;True to “true”, false to “false”.&lt;/p&gt;

&lt;h3&gt;
  
  
  Booleans to Numbers
&lt;/h3&gt;

&lt;p&gt;The “Number” constructor is the easiest way to convert a boolean to a number. “parseFloat” won’t work here as it only accepts strings.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(booleanToNumber(true)); //1
console.log(booleanToNumber(false)); //0
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you might expect, true gets converted to 1, and false gets converted to 0.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;Thanks for reading! Hopefully, with this article, you were able to get a good grasp of how to convert between primitives in TypeScript. If you liked this article, why not check out more of my&lt;a href="https://omarileon.me/blog" rel="noopener noreferrer"&gt; posts&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://www.omarileon.me/blog/typescript-primitive-conversion" rel="noopener noreferrer"&gt;&lt;em&gt;https://www.omarileon.me&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>coding</category>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Understanding “As Const” in TypeScript</title>
      <dc:creator>Omari</dc:creator>
      <pubDate>Wed, 31 Jan 2024 11:19:56 +0000</pubDate>
      <link>https://forem.com/marileon/understanding-as-const-in-typescript-4pm9</link>
      <guid>https://forem.com/marileon/understanding-as-const-in-typescript-4pm9</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8DdhxeU5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/0%2AM60_3sqRkXQix4LG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8DdhxeU5--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn-images-1.medium.com/max/1024/0%2AM60_3sqRkXQix4LG" alt="" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;TypeScript 3.4 introduced a new construct called “const assertions”. They tell TypeScript that your variable isn’t going to change, i.e., immutable, and that it should provide your type with as strict a type as possible. They affect different types in different ways, so in this article we’ll talk through how to use const assertions, and why they’re useful.&lt;/p&gt;

&lt;h3&gt;
  
  
  Strings/Numbers
&lt;/h3&gt;

&lt;p&gt;Adding “as const” to a string/number will narrow the type to a specific value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let foo = 'foo'; 
// let foo: string 
let foo = 'foo' as const; 
// let foo: 'foo't
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Or for numbers:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let foo = 7; // let foo: number 
let foo = 7 as const; // let foo: 7;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It’s less useful for strings/numbers, since usually you could just define your variable using “const” for the same effect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let foo = 7; // let foo: number 
const foo = 7; // const foo: 7;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the added benefit of runtime safety.&lt;/p&gt;

&lt;p&gt;Sometimes you might not want to define a value as a variable though and you might just want to use a string literal, e.g. for returning a value. Then, “as const” does come in use. Take a look at this example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Colour = 'red' | 'green' | 'blue';
type Variant = 'light' | 'dark';
function createColourVariant(colour: Colour, variant: Variant) {
    return `${variant}-${colour}`;
} //function createColourVariant(colour: Colour, variant: Variant): stringty
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A simple function to create a colour variant name, imagine defining a palette for an app or something similar. The return type we get from this function is just a string.&lt;/p&gt;

&lt;p&gt;You could create an explicit type for these colour variants:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type ColourVariant = `${Variant}-${Colour}`; //"light-red" | "light-green" | "light-blue" | "dark-red" | "dark-green" | "dark-blue" function createColourVariant(colour: Colour, variant: Variant): ColourVariant { return `${variant}-${colour}`; }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That might work fine for your use case, but we can also skip creating the type altogether with a const assertion:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createColourVariant(colour: Colour, variant: Variant) {
    return `${variant}-${colour}` as const;
} //function createColourVariant(colour: Colour, variant: Variant): "light-red" | "light-green" | "light-blue" | "dark-red" | "dark-green" | "dark-blue"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Which is better? The first option is useful if you plan to reuse your type a lot, and also if you want the function to adhere to the type, rather than the type depending on that variable. The second option is shorter, and lets you skip the extra work of defining an extra type.&lt;/p&gt;

&lt;p&gt;Something important to note is that you can only use “as const” with literal values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const foo = 'foo' as const;
const bar = foo as const; //A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Objects
&lt;/h3&gt;

&lt;p&gt;Objects and arrays are where “as const” gets more interesting. For objects, “as const” changes all of the properties to readonly and narrows the values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myObject = { foo: 'bar', baz: 7 };
/* const myObject: { foo: string; baz: number; } */ 
const myObject = {
    foo: 'bar',
    baz: 7,
} as const; /* const myObject: { readonly foo: "bar"; readonly baz: 7; } */
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This means you won’t be able to change the values of the properties:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myObject = { foo: 'bar', baz: 7 } as const;
myObject.baz = 6; //Cannot assign to 'baz' because it is a read-only property
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And you’ll lose access to any of the methods that mutate objects/arrays:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const me = { name: 'Omari', hobbies: ['coding', 'cooking', 'gaming'] } as const; //time to grow up :(
me.hobbies = ['coding', 'cooking']; //Cannot assign to 'hobbies' because it is a read-only property.
me.hobbies.pop(); //Property 'pop' does not exist on type 'readonly ["coding", "cooking", "gaming"]'. 
// yippee :)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Arrays
&lt;/h3&gt;

&lt;p&gt;“as const” turns arrays into tuples of readonly values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const goodLanguages = ['typescript', 'csharp']; //const goodLanguages: string[] const goodLanguages = ['typescript', 'csharp'] as const; 
//const goodLanguages: readonly ["typescript", "csharp"]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Not sure what a tuple is? Essentially it’s an ordered array of values. They’re useful for grouping variables together like an object, but a little less work.&lt;/p&gt;

&lt;p&gt;So it’s especially useful for creating and handling tuples, because “as const” preserves the order and number of items in the array. Think of creating a custom React hook for toggling a value:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function useToggle(defaultValue = false) {
    const [active, setActive] = useState(false);
    const toggle = () =&amp;gt; setActive((v) =&amp;gt; !v);
    return [active, toggle];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The inferred return type of our function is this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(boolean | (() =&amp;gt; void))[]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We know our return type is a tuple where the first is the value, and the second is a function to toggle the value, but TypeScript has assumed that the value and the toggle function could be in any place, and the array could be any number of them.&lt;/p&gt;

&lt;p&gt;So using our hook doesn’t work as you’d expect:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [dialogOpen, toggleDialogOpen] = useToggle(); 
//const dialogOpen: boolean | (() =&amp;gt; void) 
//const toggleDialogOpen: boolean | (() =&amp;gt; void)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is where the “as const” steps in:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function useToggle(defaultValue = false) {
    const [active, setActive] = useState(false);
    const toggle = () =&amp;gt; setActive((v) =&amp;gt; !v);
    return [active, toggle] as const;
} //function useToggle(defaultValue?: boolean): readonly [boolean, () =&amp;gt; void]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can then use the tuple returned by our hook as expected:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [dialogOpen, toggleDialogOpen] = useToggle(); 
//const dialogOpen: boolean 
//const toggleDialogOpen: () =&amp;gt; void
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Const vs “As Const”
&lt;/h3&gt;

&lt;p&gt;Despite how similar they sound, declaring a variable as a const variable is different to adding “as const” onto the end of a variable.&lt;/p&gt;

&lt;p&gt;Declaring a const variable tells TypeScript that the reference your variable refers to will not change. Strings and numbers in JavaScript are immutable, so if you’re declaring a variable either way then for TypeScript, there is no difference between the two techniques. The difference lies in the fact that “const” is a JavaScript feature, whereas “as const” is a TypeScript feature.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const link = 'youtu.be/pHqC0uoatag'; 
//const link: 'youtu.be/pHqC0uoatag'; 

let link = 'youtu.be/pHqC0uoatag' as const; 
//let link: "youtu.be/pHqC0uoatag"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Running the following code with Bun, for example. This will run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let link = 'youtu.be/pHqC0uoatag' as const; 
//const link: 'youtu.be/pHqC0uoatag'; 
link = ''; 
//Type '""' is not assignable to type '"youtu.be/pHqC0uoatag"'.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But this will not:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const link = 'youtu.be/pHqC0uoatag'; 
//const link: 'youtu.be/pHqC0uoatag'; 
link = ''; 
//Cannot assign to 'link' because it is a constant.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For objects and arrays, the difference lies in references vs values. Declaring an object/array using const tells TypeScript and JavaScript that that variable will never refer to another object/array, it does not mean that the values won’t change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const bestNumbers = [1, 12, 24]; //great numbers 
bestNumbers = [1, 7, 8]; //won't work, this is a different array 
bestNumbers = [1, 12, 24]; //won't work, this is a different array 
//Cannot assign to 'bestNumbers' because it is a constant. 
bestNumbers.pop(); //Works fine
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can modify the values in an object/array without modifying the reference.&lt;/p&gt;

&lt;p&gt;Compared to “as const”, where you can’t change the reference, or the values:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const bestNumbers = [1, 12, 24] as const; //great numbers 
bestNumbers = [1, 7, 8]; //won't work, this is a different array 
bestNumbers = [1, 12, 24]; //won't work, this is a different array 
//Cannot assign to 'bestNumbers' because it is a constant. 
bestNumbers.pop(); //Now this won't work either 
bestNumbers[2] = 7; //Or this
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Con(st)clusion
&lt;/h3&gt;

&lt;p&gt;So to sum everything up, “as const” or const assertions are a great TypeScript feature for giving your variables narrower types. They’re not always necessary, but they’re a great feature to have in your toolbelt, especially for creating tuples, and returning values with narrower types form functions. Hopefully, after this article, you now know when and where to use them. Thanks for reading!&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Originally published at&lt;/em&gt; &lt;a href="https://omarileon.me/blog/typescript-as-const"&gt;&lt;em&gt;https://www.omarileon.me&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>programminglanguages</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
