DEV Community

Cover image for TypeScript Playground
burak
burak

Posted on

TypeScript Playground

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

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

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

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);

Enter fullscreen mode Exit fullscreen mode

or

let userName : string = "burak"

console.log(userName);
Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-05 at 4.14.50 PM

  • 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.")
Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-05 at 4.33.52 PM

enum declaration

enum Gender{
    Male = 0,
    Female
}

console.log(Gender.Female)

console.log(Gender[0])

Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-05 at 4.41.05 PM

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])
Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-06 at 12.13.42 PM

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

Enter fullscreen mode Exit fullscreen mode

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();

Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-05 at 5.10.06 PM

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

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

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}`);
Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-05 at 5.25.45 PM

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

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}`);

Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-05 at 5.26.41 PM

  • 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();

Enter fullscreen mode Exit fullscreen mode

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

// 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();

Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-05 at 6.51.24 PM

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}`);

Enter fullscreen mode Exit fullscreen mode

Screen Shot 2020-12-05 at 7.08.18 PM

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> {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

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.");
    }
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading 🧐

WhatsApp Image 2020-12-06 at 11.26.11

Top comments (0)