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

Note, that in TypeScript projects, the convention for folder naming is typically kebab-case (also known as hyphenated lowercase). This means using lowercase letters with hyphens separating words, e.g., my-project-folder

                ts-demo-project/
                ├── dist
                    # the compiled JS files
                └── src
                    # for source TS files
            
On Linux/MacOS you can use next bash oneliner:

                mkdir -p ts-demo-project/{dist,src}
            

Initialize a Node.js project

This creates a package.json file, which holds various metadata relevant to the project and keeps track of your project's dependencies and scripts
Reference: What is the file `package.json`?

            # navigate to project root folder
            cd ts-demo-project

            # create package.json with defaults
            npm init -y
        

Install project dependencies

It's usually a good idea to have TypeScript listed as a dependency in your project.

                npm install typescript --save-dev
            

Configure TypeScript

The tsconfig.json file lets you set options for the TypeScript compiler.
Inside your project directory you can generate it with some defaults using:

                # create the tsconfig.json with some default settings
                tsc --init
            
Make sure you have next options enabled:

                {
                    "compilerOptions": {
                      "target": "ES6",
                      "module": "commonjs",
                      "outDir": "./dist",
                      "rootDir": "./src",
                      "strict": true
                    },
                    "include": ["src/**/*.ts"],
                    "exclude": ["node_modules"]
                }
            

Create a simple TS file

Create the helloUser.ts in src/ folder

            let userName:string = 'Ada';
            let userAge:number = 34;

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

Compile and Run Your TypeScript Code

Use the TypeScript compiler to transpile your TS source code to JavaScript.
In root project folder:

                tsc
            
The compiled JavaScript files will be in the dist directory if you specified it in your tsconfig.json

Watching for Changes

Manually compiling TypeScript every time you make changes can be tedious.
You can use a tsc compiler in watch mode that monitors your source files for changes and automatically compiles them.

                tsc --watch
            

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: Everyday Types @typescriptlang.org

Typing - examples


            // Boolean
            let isDone: boolean = true;
            console.log(isDone);

            // Number
            let decimal: number = 6;
            let hex: number = 0xf00d;
            console.log(decimal, hex);

            // String
            let favColor: string = "black";
            console.log(favColor);

            // Array
            let array1: number[] = [1, 2, 3];
            let array2: Array<number> = [4, 5, 6, 7]; // Using generic array type
            console.log(array1, array2);

            // Tuple
            let x: [string, number];
            x = ["hello", 10];
            console.log(x[0]); // Outputs: hello
            console.log(x[1]); // Outputs: 10

            // Enum
            enum Color { Red, Green, Blue }
            let c: Color = Color.Green;
            console.log(c); // Outputs: 1 (the enum's value)

            // Object
            let someObject: object = { name: "someObject" };
            console.log(someObject);

            // Any
            let notSure: any = 4;
            notSure = "maybe a string instead";
            notSure = false;
            console.log(notSure);
        

Function Types

Function types are used to specify the types of input parameters and the return value for functions
This ensures that functions are used correctly with the expected parameters and return type, catching potential errors early.

            // The function add takes two parameters x and y, both of type number, and returns a number.
            function add(x: number, y: number): number {
                return x + y;
            }

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

            console.log( add("hello", 5) ); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.

            console.log( add(5) ); // Error: Expected 2 arguments, but got 1.

            console.log( add(2,3).toUpperCase() ); // Error: Property 'toUpperCase' does not exist on type 'number'.
        

Function Optional Parameters

In TypeScript, you can specify optional parameters for functions, which means the caller of the function is not required to provide values for those parameters.
Optional parameters are defined by appending a question mark (?) to the parameter name.

                // 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