To get started with Typescript :
To Download Typescript – https://typescriptlang.org
We are going to install Node.js – https://nodejs.org
After node is installed :
$ sudo npm install -g typescript
JavaScriptTypescript is a programming language, we just installed the compiler to turn the Typescript code in to javascript.
watch mode
You can tell typescript to keep looking for changes and keep compiling
$ tsc --watch
JavaScriptManaging the project
Run the following command to tell typescript that this is the folder and handle multiple files. It will generate tsconfig.json file
$ tsc --init
$ tsc --watch
JavaScripttsconfig.json
How compiler works for this project, this file will be used to tell typescript
We can include and exclude files in our tsconfig.json to which file to check for ts changes and which files should’nt be compiled or excluded.
{
"compilerOptions": {
"target": "es6" // which js version you want to target
"module": "commonjs",
"lib": [. // specify library f
"dom",
"es6",
"dom.iterable",
"scripthost",
],
"sourceMap": true, // helps in debugging generates sourcemaps
"outDir": "./dist", // folder to output the compiled files
"rootDir": "./src", // folder to look for files to compile
"removeComments": true, // do not emit comments to output
"noEmit": false, // do not emit output if set to true
"noEmitOnError": true, // don't generate js files if you have an error if set to true,
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict options, below options not required if this is true */
"noImplicitAny": true, // it ensures that what type of data we are passing
"strictNullChecks": true, // strict with null values
"strictFunctionTypes": true,
"strictBindAndApply": true, // Enable strict bind, call and apply
/* Additional Checks */
"noUnusedLocals": true, // Report errors on usused locals.
"noUnusedParameters": true, // Report errors on unused parameters.
"noImplicitReturns": true, // Report error where not all code paths return something
"esModuleInterop": true // generate interoperability code between commonjs and es modules
},
"exclude": [
"node_modules" // would be default, not required to add this exclude key
],
"files": [
"app.ts"
],
"include": [] // here you can specify which files/folders typescript should be compiled
}
JavaScriptLet’s create a file sum.ts
function add(<em>num1</em>: <em>number</em>, <em>num2</em>: <em>number</em>) {
return num1 + num2;
}
const result = add(2,3);
console.log('result', result);
JavaScriptNow to compile this code
$ tsc sum.ts
JavaScriptThis will create a new file sum.js
Now you can run this sum.js using node
$ node sum.js
JavaScript