TypeScriptBasics

TypeScript Overview

TypeScript Overview

Overview

Overview

TypeScript is a superset of JavaScript, which means each valid JavaScript program is a valid TypeScript program.
TypeScript compiles to clean, simple JavaScript code which runs on any browser, in Node.js, or in any JavaScript engine that supports ECMAScript 3 (or newer).
official site: typescriptlang.org

Installation

You must have nodejs installed.

			# install as global node module:
			$ sudo npm install -g typescript

			# check installation
			$ tsc -v
				Version 3.8.3
		

Usage

We can transpile TypeScript (or ES6) to ES5 using the TypeSctipt compiler
Let's have a valid ES6 file:

			class Animal {
				name:string

				constructor(name) {
					this.name = name;
				}

				eat(){
					console.log(`${this.name} is eating`);
				}

				speak() {
					console.log(`${this.name} makes an animal noise`);
				}
			}

			class Dog extends Animal {
				constructor(name) {
					super(name);
				}

				speak() {
					console.log(`${this.name} barks`);
				}
			}

			var pluto = new Dog('Pluto');

			pluto.speak();
			pluto.eat();
		
We can transpile it to ES5 just by changing its extension to .ts and:

			tsc ES6toES5.ts
		

TypeScript Features

Static typing
Interfaces
Decorators
Transpile into old ES version
many others...

Static Typing vs Dynamic typing

In dynamically typed languages(JavaScript, Python, PHP, Ruby...) types of variables are generally not known at compile time.
In a statically typed language, variables, parameters, and objects members (i.e properties and methods) have types that the compiler knows at compile time.
The compiler use that information to perform type checks and to optimize the compiled code.
TypeScript introduces static types into JavaScript!

The Benefits of Static Typing

Catch more errors at compile time (and less bugs at run time)
It helps IDEs with code-completion (IntelliSense)
Type annotations are useful for documentation, which helps large teams to collaborate
Static Typing in JavaScript makes it less "ugly" for developers coming from Java, #C, and so on.

Early errors/bug finding

TypeScript can help us to discover errors and bug-candidates while we write the program:

			let add = function(x,y) {
				console.log(x+y)
			}

			// this is legal JS call, but TypScript will raise an error:
			add(3);

			//test.ts(5,1): error TS2554: Expected 2 arguments, but got 1.
		
Note, that despite the error, the JS files is generated.

Create TypeScript Project

Create TypeScript Project

Prepare project folder structure

You have to create nex folder structure for your TypeScript Demo Project:


			ts_demo_project/
			├── dist
				# the compiled JS files
			└── src
				# for source TS files
		

You can use the next bash one-liner:


			mkdir -p ts_demo_project/{dist,src}
		

Create package.json

The package.json file holds various metadata relevant to the project.
Reference: What is the file `package.json`?

			cd ts_demo_project
			npm init
		

Create package.json

Add the next script command to package.json


			"scripts": {
				"build": "tsc",
				"start": "npm run build -- -w"
			},
		

The tsconfig.json file

Reference: What is a tsconfig.json?

			# make sure you are in the root project folder:
			pwd
			# .../ts_demo_project

			# create the tsconfig.json with some default settings
			tsc --init
		

or manually create the tsconfig.json and paste into it


			{
				"compilerOptions": {
					"outDir": "./dist/",
					"sourceMap": false,
					"module": "commonjs",
					"target": "ES5",
				},
				"exclude": [
					"node_modules"
				]
			}
		

Just make sure, that you have "outDir": "./dist/"

Create a simple TS file

Create the helloUser.ts in src/ folder

			let userName='Ada';
			let userAge=34;

			console.log(`Hello ${userName}, you are ${userAge} age old`);

		

start the project

write in your terminal:

			# make sure you're in the root project folder:
			pwd

			# start the project
			npm start
		
Now ts will compile each 'ts' file in src/ folder into respective file in dist/ folder. And that will happen on every change.

Basic Types in TypeScript

Basic Types in TypeScript

TypeScript Types

JavaScript have several native types, which also exist in TypeScript
boolean - true/false
number - integers, floats, Infinity and NaN
[] - arrays of other types
{} - object literal
undefined - for not set value
But TypeScript also adds:
enum - enumerations like { Red, Blue, Green }
any - use any type
void - nothing

Reference: Basic Types @typescriptlang.org

Typing - examples


			let start: boolean = false;
			let age: number = 16;
			let userName: string = "Ada";
			let dataList: number[] = [1, 2, 3];

			enum Color {Red, Green, Blue};
			let c: Color = Color.Green;

			let anything: any = 42;
			anything = "now I'm a string";
			anything = false;

			function showMessage(msg: string): void {
				console.log(msg);
			}
			showMessage('Howdy!');
		

Function Types

We can add types to each of the parameters and to the function's return type.
TypeScript can figure the return type out by looking at the return statements, so we can also optionally leave this off in many cases.

			function add(x: number, y: number): number {
						return x + y;
			}

			console.log( add(2,3) );
		

Function Optional Parameters


			// optional parameters:
			function greet(firstName: string, lastName?: string) {
				return lastName? `${firstName} ${lastName}`: firstName;
			}

			console.log( greet('Ada', 'Byron') );
			console.log( greet('Ada') );
		

These slides are based on

customised version of

Hakimel's reveal.js

framework