Typescript Quiz

Test your typescript knowledge

2020 Typescript Beginners Tutorial, Simple and Easy

The purpose of this tutorial is to show you how to use Typescript and the syntax associated with the correct code. In this tutorial we are going to cover:

  1. Environment Setup
  2. Variable Declarations
  3. Variable Types
  4. Functions
  5. Interface
  6. Class
  7. Access Modifiers


Environment Setup:

  • Node.js - Download
  • Typescript - Download
    If you have node.js already installed, you can install it by using this command:
    npm install -g typescript
  • Text Editor - Download
  • Browser with Developers Tools


As of May 2020, I will be using the current versions for this tutorial: Node.Js: v12.16.3 and Typescript Version 3.8.3

Variable Declarations:

  1. Visual Studio Code and open the folder where you want to save this project. Go to File > Open Folder
  2. Create new file, got to File > File
  3. Save File: go to File > Save As > index.ts
  4. Open Terminal: Terminal > New Terminal


You are all set and ready to go, lets get started

Hello World

let message = 'Hello World';

console.log(message);

Terminal Command:

tsc index


Notice on your visual code navigation panel, there is anew file created called index.js - Look at the .js file and you will see that index.ts has been compiled into JavaScript. (for example, let was changed to var)

Run the index JavaScript file:

node inde.js

OUTPUT: Hello World

in the index.ts you will see there is an error in the message variable, this is because typescript looks at this file as a module instead of a script. to make it a script att export() at the top of index.ts The index.ts should look like this:

export{};

let message = 'Hello World';

console.log(message);


Recompile:

tsc index.ts

Take a look at the index.js you will see new changes

The Watch Option - Let setup to automatically compile when the script changes: Send this command:

tsc main.ts --watch

Try it. Change the message variable value to "This is cool", save your changes and see the compile automatically update the JavaScript file. You can confirm you changes by sending this command:

node main.ts

This is was just an overview of how Typescript compiles into JavaScript. Now lets keep going.

Typescript encourages let and const for variable declarations.

JavaScript has global scope and functions scope. You can re declare variables multiple times.

Typescript you cannot re declare in let or const. for example you would get an error here:

let x = 10;
const y = 20;

let x = 30;


The main difference between let and const is that once you’ve declare the value in a const, it cannot change.

Variable Types

  • Boolean
  • Number
  • String
  • Any
  • Null
  • Undefined
  • Unknown


Examples:

Boolean:
let isBeginner: boolean = true;

Number:
let total: number = 0;

String:
let name: string = ‘Jonh’

Any:

let randomValue: any = 10;
randomValue = true;
randomValue = 'string';

Unknown: 25:00

let myVariable: unknown = 10;
console.log(myVariable.name); //
myVariable.toUpperCase(); //
(myVariable as string).toUpperCase(); // No ERROR

Typescript automatically assigne a type of variable is one is not declared. for example:

let a;
a=10; // OK
a=true; // OK

let b = 20;
b = true; // ERROR. this is because typescrpt assumed b is a number type


Template Strings Example: Be sure to use backticks, not single quotes and allow you to declare a string with multiple lines:

let sentence: string = `You name is ${}
and you are very cool`;

Note: When you have declared a typeof variable and you assign a different type of value, you will get an error. For example:

let isBeginner: boolean = true;
isBeginner = ‘a string’;

example of a null type:
let n: null = null;

Example of an undefined type:
let u: undefined = undefined;

NOTE: null and undefined are sub=types of other types because you can use null and undefined in other types. For example:
let isNew: boolean = null;
let myName: string = undefined

Arrays:

let list1: number[] = [1,2,3];

let list1: Array<number> = [1,2,3];

mixed types arrays. you cannot mix, in this example, the first element MUST be a string only.

fixed values:
let person1: [string,number] = ['john',22];

enum Color {red=5, green, blue}; // red starts at 5 an increments green to 6 ans so on
let c: Color = Color.green;
console.log(c); // OUPUT: 6

 MultiType variables lets you assign multiple type of variables:

let multiType: number | boolean; // Number or Boolean
multiType = 20;
multiType = true;

Becarful using the any types because not all methods will be supported. for example not all string methods have the same number methods:

anyType.name // for string and would not work on number
anyType.value // this method would be available to number not a string.

FUNCTIONS:

Javascript Example:

function add(num1, num2){
 return num1 + num2;
}

Typescript Example:

function add(num1:number, num2:number){
 return num1 + num2;
}

add(5,10); //returns 15
add(5,'10'); // ERROR!

add() function expecting a return MUST be a number by adding ": number" to the function

function add(num1:number, num2:number): number{
 return num1 + num2;
}

add(5,10); //returns 15
add(5,'10'); // ERROR!

Option parameters: in this example, lets say the second number is optional you can write the function as such by simply adding a question mark on the parameter mum2

function add(num1:number, num2?:number): number{
 if(num2)return num1 + num2;
else return num1;
}

add(5,10); //returns 15
add(5); // NO ERROR!

IMPORTANT: the REQUIRED parameter must always be first and any other optional can go next example: add(required,optional)

Default Parameters - are set values in the function declarations. example, num2 has a default value of 10

function add(num1:number, num2:number = 0): number{
 if(num2)return num1 + num2;
else return num1;
}

add(5,10); //returns 15
add(5); // returns 15 because num2 has a default value of 10

INTERFACES:

No interface example:

function fullName(person: {firstName: string, lastName: string}){
console.log(`${person.firstName} ${person.lastName}`);
}
let p = {
firstName = 'Bruce',
lastName = 'Wayne'
};
fullName(p); // OUTPUT: Bruce Wayne

Interface example to make our code cleaner;

interface Person{
firstName: string;
lastName: string;
}

function fullName(person: Person){
console.log(`${person.firstName} ${person.lastName}`);
}
let p = {
firstName = 'Bruce',
lastName = 'Wayne'
};
fullName(p); // OUTPUT: Bruce Wayne

NOTE: you can use the ? for optional properties.

CLASSES

There are no classes in JavaScript. Typescript uses the object oriented class based approach.

 Typescript Class Example:

class Employee {
    employeeNamestring//variable type of string
    constructor(namestring){
        this.employeeName = name;
    }
    greet(){
        console.log(`Good day ${this.employeeName}`);
    }
}

let emp1 = new Employee('John');
console.log(emp1.employeeName); 
// OUTPUT: Good day John

HboT8g_QSGc

The syntax should look familiar if you have used C# or Java before.
We have declared a class called Employee
The class has three memebers
Property: employeeName
Constructor
Method

Now that we have declared this class, we can create an instance of the class.

Class-based inheritance 43:03

To use inheritance, use we the extends keyword. Example class with inheritance:

let emp1 = new Employee('John');
console.log(emp1.employeeName); // OUTPUT: Good day John

class Manager extends Employee{
    constructor(managerNamestring){
        super(managerName);

    }
    delegateWork(){
        console.log(`Manager delegating tasks`);
    }
}
let m1 = new Manager('Bruce');
m1.delegateWork(); // OUTPUT: Manager delegating tasks
m1.greet(); // OUTPUT: Good day John
console.log(m1.employeeName); // OUTPUT: John

Modifiers

Access Modifiers are keywords that set the accessibility of properties and methods in a class, there are three:

  1. Public
  2. Private
  3. Protected

* The default class member is public.

  1. Public - you can access this modifier throughout the script
  2. Private - If you declare a class member as private, you cannot access it from outside the containing class
  3. Protected - you can access protected class members from within a class but not outside the containing class

In our example class above, this is how you would declare a member with its access modifier:

class Employee{
    private EmployeeNamestring;

These are my notes for learning Typescript. I will use this as a reference. and you can too.

 Good luck.