Welcome to your first TypeScript Program. So, in this tutorial, you learn to write a simple program in TypeScript, compile it and then use it on the web page.
Now, create a new file in your code editor and name it sum.ts and write the code below in it.
function addNumbers(a: number, b: number) {
return a + b;
}
var sum: number = addNumbers(10, 15)
console.log('Sum of the two numbers is: ' +sum);
The TypeScript code above defines the addNumbers() function, calls it, and logs the result in the browser's console.
At this point, open the command prompt on Windows (or a terminal on your platform), navigate to the path where you saved add.ts, and compile the program by making use of the command below.
tsc sum.ts
Now, the command above will compile the TypeScript file sum.ts and create the Javascript file named sum.js at the same location. So, the sum.js file contains the code below.
function addNumbers(a, b) {
return a + b;
}
var sum = addNumbers(10, 15);
console.log('Sum of the two numbers is: ' + sum);
From the above code, you will notice that the TypeScript compiler compiled the add.ts TypeScript file into the Javascript file sum.js. Now, you can include the sum.js file in a web page using a script tag and see the result in the browser's developer console.
So, let us see how TypeScript compiles the program when we pass a string parameter to the addNumbers() function rather than a number.
Now, replace var sum:number = addNumbers(10, 15) in add.ts with var sum:number = addNumbers(10,'abc') and then recompile the add.ts file in the terminal. But, you will get the compilation error, as shown below:
C:> tsc sum.ts
add2.ts(5,32): error TS2345: Argument of type 'abc' is not assignable to parameter of type 'number'.
Remember that TypeScript does not compile the code if you pass a string to a function that is expecting a number, as most IDE will display TypeScript errors instantly without compiling the code at first.
Therefore, static type-checking with type annotations and several other TypeScript features like interface, class, and module assists developers or programmers to write cleaner and more scalable code that can be shared across project teams.