Typescript first Code

In this Post, I’m going to show you how to install TypeScript, and write your first TypeScript program.

So here,n the terminal, we’re not going to work with Angular in this section, we’re going to purely focus on TypeScript. So first we need to install TypeScript globally on our machine. install -g, which stands for global, typescript. if you’re on Mac, you need to put sudo at the front.

Now we can type tsc, which stands for TypeScript Compiler

npm install -g typescript

Alright, now I’m going to create a new folder for this section, so let’s call ts-hello. Let’s go to this folder, now here I’m going to create a new file call main.ts, and open it with vs code. So, code main.ts. So now I’m going to write some plain JavaScript code, and I want to show you that all this JavaScript code is also valid TypeScript code, so first I’m going to define a function. that takes a message and here we simply log that message on the console like this.

// main.ts
function log(message) {
	console.log(message)
}

var message = "Hello world";

log(message)
tsc main.ts

Then I’m going to declare a global variable, let’s call this.message, and set it to this string, Hello World. And finally call our log function, message. So this is just plain JavaScript code, right?
Save, back in the terminal, we need to Transpile this TypeScript file into JavaScript, so tsc, or TypeScript Compiler, main.ts. Now, if you look at the files in this folder, look what we have main.js, and main.ts. Now this Transpilation, or compilation step, when you are building an Angular app, happens under the hood, so you don’t have to manually call the TypeScript, compiler. In fact when you run your application using ng serve, Angular CLI, calls TypeScript compiler under the hood, to transpile all of our TypeScript code. open our main.js file. So code.main.js. So it’s exactly the same code that we wrote but now it’s in a JavaScript file. So all JavaScript code is also valid TypeScript code. Now back in the terminal, I can execute this code using node. So node, main.js And we got the Hello World message on the console.

by kushan