TypeScript Playground
Tags: typescript, javascript, tutorial
Published: 2020-12-06 09:35:41

Hi everybody, good morning post lovers. I hope you are good today. Today I'm gonna explain the Typescript programming language's basic features. I like to write Typescript. Actually Typescript syntax almost similar to C# programming languages syntax. 

Have you ever visited the Playground 👉 If you say no 🖱 to the Url [PlayGround](https://www.typescriptlang.org/play?#code/PTAEHUFMBsGMHsC2lQBd5oBYoCoE8AHSAZVgCcBLA1UABWgEM8BzM+AVwDsATAGiwoBnUENANQAd0gAjQRVSQAUCEmYKsTKGYUAbpGF4OY0BoadYKdJMoL+gzAzIoz3UNEiPOofEVKVqAHSKymAAmkYI7NCuqGqcANag8ABmIjQUXrFOKBJMggBcISGgoAC0oACCoASMFmgY7p7ehCTkVOle4jUMdRLYTqCc8LEZzCZmoNJODPHFZZXVtZYYkAAeRJTInDQS8po+rf40gnjbDKv8LqD2jpbYoACqAEoAMsK7sUmxkGSCc+VVQQuaTwVb1UBrDYULY7PagbgUZLJH6QbYmJAECjuMigZEMVDsJzCFLNXxtajBBCcQQ0MwAUVWDEQNUgADVHBQGNJ3KAALygABEAAkYNAMOB4GRogLFFTBPB3AExcwABT0xnM9zsyhc9wASmCKhwDQ8ZC8iElzhB7Bo3zcZmY7AYzEg-Fg0HUiS58D0Ii8AoZTJZggFSRxAvADlQAHJhAA5SASAVBFQAeW+ZF2gldWkgx1QjgUrmkeFATgtOlGWH0KAQiBhwiudokkuiIgMHBx3RYbC43CCJSAA) 

# What is TypeScript?

TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript.[4] As TypeScript is a superset of JavaScript, existing JavaScript programs are also valid TypeScript programs. [More detail](https://en.wikipedia.org/wiki/TypeScript)

TypeScript is an open-source language that builds on JavaScript, one of the world’s most used tools, by adding static type definitions. [More detail](https://www.typescriptlang.org/)

# A few pros
  * Easier to read and understand
  * All the benefits of ES6 (ECMAScript 6)
  * Rich IDE Support
  * Support interface and static 

# Basic data types with samples

* String 
  
Represent a sequence of Unicode characters.

```
let userName : string 

userName = "burak";

console.log(userName);

```
or

```
let userName : string = "burak"

console.log(userName);
```
![Screen Shot 2020-12-05 at 4.14.50 PM](https://dev-to-uploads.s3.amazonaws.com/i/45i2u5cl0hr7s7q3spt8.png)

* Boolean (true or false)

Represent logical value.

` let isCheckTermsOfCondition : boolean = false; `

* Number (floating points, bignumbers)

Double precision 64-bit floating-point values. It can be used to represent both, integers and fractions

` let age : number = 30; `

**backtick with embedded expression**
```
let firstName : string = "Burak"
let lastName : string = "Seyhan"
let age : number = 30

let result : string = `Hi, I'm ${firstName} ${lastName}. I'm ${age} years old.`
console.log(result)

console.log("Hi, I'm " + firstName + " " + lastName + "." + "I'm " + age + "years old.")
```
![Screen Shot 2020-12-05 at 4.33.52 PM](https://dev-to-uploads.s3.amazonaws.com/i/3nfpj9l666dpceswrgc8.png)
 
# enum declaration 

```
enum Gender{
    Male = 0,
    Female
}

console.log(Gender.Female)

console.log(Gender[0])

```
![Screen Shot 2020-12-05 at 4.41.05 PM](https://dev-to-uploads.s3.amazonaws.com/i/5htgngqy5uxzw9tcjkmn.png)

# Tuple declaration

Tuple can contain two values of different data types.

` var brands: [number, string] = [1, "Apple"] `

Let's define a tuple array. Tuple working like index [index].

```
var cars: [number, string][];
cars = [[1, "Polo"], [2, "Tiguan"], [3, "T-Roc"]];

console.log(cars[0])
console.log(cars[1])
console.log(cars[2])
```
![Screen Shot 2020-12-06 at 12.13.42 PM](https://dev-to-uploads.s3.amazonaws.com/i/wuf7s0v4v5cizif5m7mm.png)

# Declare functions and arrays

```
function function_name(){

}

function function_name(datatypeName:datatype){

}

function function_name(datatypeName:datatype) : return type{

} 

array declarations

// var names : string[] = [] empty string array

```
Let's create functions with names array.

var names : string[] = ["Burak", "Burak_1", "Burak_2", "Burak_3"]

```
function getNames(){
    for(var n of names)
        console.log(n)
}

getNames();

```

![Screen Shot 2020-12-05 at 5.10.06 PM](https://dev-to-uploads.s3.amazonaws.com/i/szk2730prd3a3p6wijde.png) 

After that, I added new names with the push method.
 
` names.push("Client"); `
` names.push("Client_1"); `

Then call the getNames() method again

![Screen Shot 2020-12-05 at 5.11.37 PM](https://dev-to-uploads.s3.amazonaws.com/i/lgvch9dsqcj0miki3bk5.png)

# Declaration of comment

//code line

/*
  code blocks
*/
 
# Class, Constructor, and Function 

* Class declaration

In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior. [More detail](https://en.wikipedia.org/wiki/Class_(computer_programming))

Like C#,  if you wanna class objects you have to instantiate with **new** keyword.

```
class Catalog{
    name : string = ""
    description : string = ""
}

var catalog = new Catalog();

catalog.name = "Electronic";
catalog.description = "...";

console.log(`CatalogName: ${catalog.name} Description: ${catalog.description}`);
```
![Screen Shot 2020-12-05 at 5.25.45 PM](https://dev-to-uploads.s3.amazonaws.com/i/iu98pbygriyh7nq61t6y.png)

# Constructor declaration

In class-based object-oriented programming, a constructor *(abbreviation: ctor)** is a special type of subroutine called to create an object. [More detail] (https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming))

Thus, you can create multiple constructors. 

```
class Catalog{
    name : string 
    description : string

    constructor(name: string, description: string){
        this.name = name;
        this.description = description;    
    }
}

var catalog = new Catalog("Cloths","...");

console.log(`CatalogName: ${catalog.name} Description: ${catalog.description}`);

```
![Screen Shot 2020-12-05 at 5.26.41 PM](https://dev-to-uploads.s3.amazonaws.com/i/tx9ucyerp82c3t4uqg4b.png)
 
* Function declaration

```
class Product{
    name : string 
    unitsInStock : number

    constructor(name: string, unitsInStock: number){
        this.name = name;
        this.unitsInStock = unitsInStock;    
    }

     getInformation(){
        console.log(`Product Name: ${this.name}
                     UnitsInStock: ${this.unitsInStock}`);
    }
}

var product = new Product("Macbook 13.inc", 34);

product.getInformation();

```
# Inheritance 

In TypeScript, we can use common object-oriented patterns. One of the most fundamental patterns in class-based programming is being able to extend existing classes to create new ones using inheritance. [More detail](https://www.typescriptlang.org/docs/handbook/classes.html#inheritance)

```
// base class
class Fligth{
    protected from : string
    protected to : string
    protected flightnumber : string
    protected numberOfPassenger : number
    constructor(from:string, to:string, 
                number: string,passenger: number){
        this.from = from;
        this.to = to;
        this.flightnumber = number;
        this.numberOfPassenger = passenger
    }
}

class XAirlines extends Fligth{
    fligthDetails(){
        console.log(`From ${this.from}}, To ${this.to},
                     Fligth Number ${this.flightnumber} NumberOfPassenger ${this.numberOfPassenger}
                     Delay ${this.isDelay}`);
    }
}

class ABCAirlines extends Fligth{
    fligthDetails(){
        console.log(`From ${this.from}}, To ${this.to},
                     Fligth Number ${this.flightnumber} NumberOfPassenger ${this.numberOfPassenger}
                     Delay ${this.isDelay}`);
    }
}

class WinterAirlines extends Fligth{
    
    isDelay = true
    
    constructor(data: {from:string, to:string, number: string,passenger: number}){
        super(data.from, data.to, data.number, data.passenger);

    }

    fligthDetails(){
        console.log(`From ${this.from}}, To ${this.to},
                     Fligth Number ${this.flightnumber} NumberOfPassenger ${this.numberOfPassenger}
                     Delay ${super.isDelay}`);
    }
}

var xairlines = new XAirlines("Istanbul","Berlin","23SD98",135);
xairlines.fligthDetails();

var abcAirlines = new ABCAirlines("Ankara","Holland","3311BS",70);
abcAirlines.fligthDetails();

var winterAirlines = new WinterAirlines({from:"Istanbul",to:"Poland",number:"2311BS",passenger:223});
winterAirlines.fligthDetails();

```
![Screen Shot 2020-12-05 at 6.51.24 PM](https://dev-to-uploads.s3.amazonaws.com/i/ohl0xpsp8a8a2k0stflf.png)
 
# Interface declaration

```
interface UserService{
    emailAddress:string
    firstName : string
    lastName :string

    Login(email:string) : User 
}

class User **implements** UserService {
    
    emailAddress: string;
    firstName: string;
    lastName!: string;

    constructor(email: string, firstName: string, lastName: string){
        this.emailAddress = email
        this.firstName = firstName
        this.lastName = lastName
    }

    Login(email: string): User {
        return new User(email, this.firstName, this.lastName);
    }
}

var user = new User("burakseyhan8@gmail.com","burak","seyhan");
    
    console.log(`Email Address ${user.emailAddress} FirstName ${user.firstName} LastName ${user.lastName}`);

```
![Screen Shot 2020-12-05 at 7.08.18 PM](https://dev-to-uploads.s3.amazonaws.com/i/f3t8i8r2mu7hm7c89j15.png)

# Generics 

Typescript also has generic like C#. Here is the key **DRY** so if you need the same method in a different class you should use the base interface.

Here is the definition of generics

```
interface interfaceName<T> {
    // ...
}

interface interfaceName<T,L> {
    // ...
}
```

Let's write some examples.

```
interface Repository<T> {
    GetItems(): T[];
    GetItem(id: number): T;
    Remove(id: number): boolean;
    Save(item: T): T;
}

declare class Person {
   //properties here
}

declare class PersonService implements Repository<Person> {  
    GetItems() {
        throw new Error("Method not implemented.");
    }
    GetItem(id) {
        throw new Error("Method not implemented.");
    }
    Remove(id) {
        throw new Error("Method not implemented.");
    }
    Save(item) {
        throw new Error("Method not implemented.");
    }
}
```

Thank you for reading 🧐

![WhatsApp Image 2020-12-06 at 11.26.11](https://dev-to-uploads.s3.amazonaws.com/i/an4l8r07sbi1hweoi3db.jpeg)