In the above example, we have declared a function with the name sum that accepts argument a and b. It performs arithmetic sum operation on these two operands and returns a result.

In an ideal situation, these two arguments must be numbers or values of the type number to be precise. But JavaScript doesn’t stop you from passing any other values as arguments to the function call. That’s why sometimes you can see [NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) as the return value when arithmetic operations are performed on non-number values.

Also, we expect the return value of this function to be a number but JavaScript won’t stop you from treating it differently. For example, in the above program, we have called [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) method on the expected return value of type number but is a prototype method of a string value. Luckily, the return value was a string (not ideal though) and our program did not crash.

As you can see, the program above is not ideal to run in mission-critical situations. We need to know if our program can work safely before it is deployed to the mission. This is where TypeScript can help us. Before compiling the program, TypeScript walks through each function call of sum and checks if arguments are all right. Let’s redesign the program above.

#web-development #typescript #programming #javascript #nodejs

TypeScript — Functions
1.25 GEEK