Use safeParseTo function to Type Strongly your TypeScript Code

<p>Adding TypeScript to JavaScript, it is no longer a choice but an obligation to have a robust code.</p> <p>Let me show you how to strongly type your code with the&nbsp;<strong>safeParseTo&nbsp;</strong>function.</p> <h1>Without Using safeParseTo</h1> <p>Let&rsquo;s imagine, we have a function that accept a string/number list. It doubles all numbers and returns the new list.</p> <pre> const list: (number | string)[] = [1, 2, &quot;hi&quot;, 3, &quot;hello&quot;]; const doubleNumberInList = (_list: (number | string)[]) =&gt; _list.map((e) =&gt; { if (typeof e !== &quot;number&quot;) { return e; } return e * 2; }); console.log(doubleNumberInList(list));</pre> <p>Inside this function, of course, we check if the element is a number and after double it.</p> <p>The code above work well, but our code is not really clean.</p> <p>Why? Because we don&rsquo;t respect the single responsibility principle. Let&rsquo;s make it cleaner.</p> <p>We have to go out the code that check if the element is a number and the code that double the number.</p> <p><a href="https://blog.stackademic.com/use-safeparseto-function-to-type-strongly-your-typescript-code-7dc602999c15">Visit Now</a></p>