TypeScript Installation And Create First Application
TypeScript installation
Two main ways to install the TypeScript,
Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. We can download and install the TypeScript from this link.
Just add a : string type annotation to the ‘msg’ function argument,
- Using npm (Node package manager)
- By installing TypeScript’s Visual Studio plugins
Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. We can download and install the TypeScript from this link.
npm install -g typescriptTo check the installation version, the following command can be used,
tsc -version
Creating first TypeScript Application
Write the following code in a file with the .ts extension (let the name be message.ts).
function showMessage(msg) { return "Welcome to " + msg; } let msg = "TypeScript"; console.log(showMessage(msg));
Compile the .ts code
We can compile the above code using the following command,
tsc message.ts
A new file with name message.js is created, with the following equivalent JavaScript content.
function showMessage(msg) { return "Welcome to " + msg; } var msg = "TypeScript"; console.log(showMessage(msg));
Execute this file using the following command,
node message.js
The .ts file is eventually transpired into a .js file, that can be run on any browser, host, or OS.
Type Annotations
Both the files above, message.ts, and message.js are exactly the same. We can add type annotations to this function message. The Type Annotations in TypeScript are lightweight ways to store the desired contract of the function or variable. In our message function, we intend to take in a string parameter.
function showMessage(msg : String) { return "Welcome to " + msg; } let msg = "TypeScript"; console.log(showMessage(msg));
Passing argument having type other than String will result in an error on the compilation for the above code.