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 <strong>safeParseTo </strong>function.</p>
<h1>Without Using safeParseTo</h1>
<p>Let’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, "hi", 3, "hello"];
const doubleNumberInList = (_list: (number | string)[]) =>
_list.map((e) => {
if (typeof e !== "number") {
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’t respect the single responsibility principle. Let’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>