TypeScript Basics
1. What is TypeScript?
JavaScript was developed as a language for client-side. The development of Node.js has made
JavaScript as an option for server-side technology too. But, as JavaScript program grows it
start being messier, becomes difficult to maintain the code. Moreover, these discomforts
prevented JavaScript from succeeding at the enterprise level. Then TypeScript was introduced
to bridge this gap.
TypeScript follows object oriented programming(OOP) paradigm. TypeScript can also be said as
the superset of JavaScript.
But ultimately JavaScript code runs in the system. This is done by Transpiling TypeScript code into
JavaScript code with the help of TSC(TypeScript Compiler).
2. Why use TypeScript?
TypeScript is far better than its competition like CoffeeScript and Dart, as in TypeScript is superset of JavaScript.
1. JavaScript code is simplified by TypeScript, making it a lot easier to read and debug.
2. It is open-source.
3. It is not just a programming language, but also provide a lot of developement tools.
4. Type checking is done in TypeScript, which helps developers to avoid painful bugs.
5. It saves a lot of time of a developer.
6. TypeScript supports OOP paradigm.
7. TypeScript is compiled language.
3. Installing TypeScript
Installing TypeScript is very easy and that can be done via npm, you just have to open your terminal and type some command as:
npm install typescript
This command installs TypeScript locally for a specific project. And if you want to install TypeScript
globally in your system i.e for all the projects you will be doing, you must use following command:
npm install -g typescript
4. A simple TypeScript program
Above mentioned is a simple typescript program. We need to compile this program to get the result we want. So, to compile we can use the following command;
After compiling the helloworld.ts file TSC transpiles the .ts file into .js file and a new helloworld.js file is created as;
Now this .js file runs in the system and result is obtained. To run this js file command used is;
5. Use of tsc --init command
This command creates a configuration file called tsconfig.json. tsconfig.json file defines the root files and the options available for compiler which is required to compile the project. Also we can compile all the .ts file at a single go using just tsc command. We don't have to mention name of the file every time we want to compile them.
5. Use of export and import
In TypeScript modules are executed within their own scope,
which means variables, functions, classes, etc. declared in a module
are not visible or accessed outside the module. To access them outside the scope we need to explicitly export them
using one of the export forms. And to consume the exported variable,
function, class, interface, etc.
we need to import them using one of the import forms.
Syntax to export:
Syntax to import:
ConversionConversion EmoticonEmoticon