- Certainly! Here's an example of TypeScript code that calculates the sum of two numbers:
// sum.ts
// Declare a function that takes two numbers as parameters and returns their sum
function sumNumbers(a: number, b: number): number {
return a + b;
}
// Call the sumNumbers function with two numbers
const num1: number = 5;
const num2: number = 10;
const result: number = sumNumbers(num1, num2);
// Output the result
console.log(`The sum of ${num1} and ${num2} is: ${result}`);
- To run this TypeScript program and see the sum of two numbers:
- Save the above code in a file called `sum.ts`.
- Open a Command Prompt or PowerShell window.
- Navigate to the directory where you saved `sum.ts`.
- Run the TypeScript compiler (`tsc`) command to compile the TypeScript file into JavaScript:
tsc sum.ts
- This will generate a JavaScript file called `sum.js` in the same directory.
- Finally, you can run the JavaScript file using Node.js:
node sum.js
- You should see the output:
The sum of 5 and 10 is: 15
- That's it! You have successfully written and executed TypeScript code to calculate the sum of two numbers.
No comments:
Post a Comment