TypeScript: Multiply Two Numbers

1. Introduction

TypeScript is not just a strict syntactical superset of JavaScript; it also brings strong type-checking and object-oriented capabilities to JavaScript. In this article, we'll explore the basic arithmetic operation of multiplication and see how TypeScript's type system ensures a smooth experience.

2. Program Steps

In this program, we will:

1. Define a function named multiply that will take in two numbers and return their product.

2. Use TypeScript's type annotations to ensure only numbers are passed to the function.

3. Test the function with some sample numbers and display the result.

3. Code Program

// Function to multiply two numbers
function multiply(num1: number, num2: number): number {
    return num1 * num2;
}
// Using the function and displaying the result
console.log(`The product of 8 and 6 is: ${multiply(8, 6)}`);

Output:

The product of 8 and 6 is: 48

4. Step By Step Explanation

1. We start off by defining our multiply function. With TypeScript, we can provide type annotations, denoted by the : number syntax. This ensures that our function can only receive numbers as arguments, offering a layer of protection against potential errors.

2. Inside the multiply function, we return the product of num1 and num2.

3. To see our function in action, we invoke it with two numbers, 8 and 6. Using a template literal (a feature from ES6), we embed the function call inside a string and log the resulting message to the console.

Comments