Use safeParseTo function to Type Strongly your TypeScript Code

Adding TypeScript to JavaScript, it is no longer a choice but an obligation to have a robust code.

Let me show you how to strongly type your code with the safeParseTo function.

Without Using safeParseTo

Let’s imagine, we have a function that accept a string/number list. It doubles all numbers and returns the new list.

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));

Inside this function, of course, we check if the element is a number and after double it.

The code above work well, but our code is not really clean.

Why? Because we don’t respect the single responsibility principle. Let’s make it cleaner.

We have to go out the code that check if the element is a number and the code that double the number.

Visit Now