Tuesday, October 12, 2021

Login with Twitter API With Angular


Step-By-Step Guide To Connect Twitter API With Angular

APIs are one most useful tools to streamline and optimize features in an application. Using the Twitter API, you can practically access all the features of the social media platform and make your app more accessible to Twitter users.

While using any application, have you ever come across an option with you could log in or sign up or get details about your Twitter timeline on a 3rd party website? Well, all these things happen because of Twitter API.

It does not only make an application more robust but user-friendly to the end-user. In addition to that, you also need to think about the Cost To Make An App as well.

If you also want to include such features in your application, we have got a guide for you. We are going to connect Twitter API using Angular JavaScript using a step-by-step guide.

Along with the Angular, we are also going to use Node.js to create the server. You might ask that out of all of the other programming languages, why are we using Angular?

We have got our reasons along with the varied experience of the software development industry that made us believe that AngularJS is the perfect choice for this purpose.

Let’s understand why to use AngularJS.

Reasons To Use AngularJS

Excellent MVC Support

Most of the programming languages out there require developers to decompose their programs into specific model-view-controller.

Once they have written the code, they have to amalgamate everything to ensure that the program is written correctly.

But whenever you are using Angular, the program is automatically compatible with the modern-view-controller architecture. So, developers don't have to waste so much amount of time to connect the dots.

Highly Scalable

The traditional programming languages are still struggling in scaling web applications.

If you're working with CSS, HTML, and the native JavaScript, then scaling your existing web applications might be extremely tough for you.

Because it would not only result in an extended amount of code but also require additional resources and time.

However, when it comes to Angular, the way this JavaScript framework has been built makes it the best suitable for all the programming needs.

It is highly scalable yet compact to be used for building enterprise-level or necessary applications.

Reusability at its Best

Usability is one of the essential advantages of using AngularJS for programming.

All the code written in the Angular framework are entirely reusable and can be utilized for other applications as well.

Unlike other additional programming languages that make you write the whole code again, even for similar features or code every single time, AngularJS takes off that burden by making the code 100% reusable.

You can practically copy and paste your code to use it in other places effectively.

You don't need to keep writing similar code for your application. You can dynamically utilize the code and save a lot of time and resources for the application development.

Time-Saving

This is arguably my favorite reason as to why using Angular for programming needs.

Developers and entrepreneurs would agree that time when is the most vital element to ensure efficient product development.

When it comes to programming, you will have to invest a lot of time to get the required application for yourself.

Whenever you are working with HTML, CSS, or native JavaScript, the time required to build the whole application is considerably higher compared to the time necessary to create the same application using AngularJS.

Thus, the Angular JavaScript framework helps developers save a lot of time because of its optimized build.

The programming elements which take so much amount of time in the native language can be easily made using this JavaScript framework.

Cost-Effective

This is another vital advantage of using AngularJS for front end development.

Along with its faster development capability, programming style and language used to write code in Angular are heavily practiced in the programming industry.

HTML, CSS, and JavaScript developers can quickly write code in AngularJS.

Therefore, companies and agencies don't have to look for highly skilled and unique human resources because the existing web developers can comfortably write code in AngularJS.

That's why they don't have to increase the wages of the developers or go for specific developers to do the job. Moreover, they don't have to install specific hardware or software required to write code in Angular JS.

I hope these reasons are enough to make you believe that why Angular is the ideal choice for programming.

Today, we are going to build an app with Twitter API by using Node and Angular 6.

By the end of the guide, you will have a tool:

  1. That would authenticate a Twitter user
  2. That can share Tweets using the Twitter API
  3. That can read the Twitter timeline with the same API
  4. That can also give you a list of recent tweets by the authenticated user
  5. That can also get a list of tweets where the user is mentioned
  6. And I can do other few things!

So without further ado, let’s dive straight in.

Steps To Connect Twitter API With Angular

Steps-To-Connect-Twitter-API.jpg

Step 1: Install the Required Files

Before you start building an application that connects with the Twitter API using Angular, make sure that you have enough tools installed in your system.

For this particular example, we are going to use Node and Angular JavaScript frameworks.

Therefore, you need to install Node and Angular JavaScript frameworks in your computer systems. There are enormous resources available online resources that can give you practical guidance on how to install these frameworks on any system.

Step 2: Create a Node Server

First, we will build a Node server that could help us interact with Twitter API with the maximum potential.

Since we are connecting the Twitter API, we will require credentials to access the API of one of the largest social media platforms by registering an application on their official website.

You need to go app.twitter.com to register an application first.

On this landing page, you will be asked to enter necessary details like URL, application name, and description.

Once you create your application, you will be required to create unique keys for your app.

Go to Keys and Access Token to create your access token. When you go to that tab, you will find Create my access token located at the bottom of the page.

You will get four keys like below generated by the app:

  • Consumer Key (the API key)
  • Consumer Secret (the API secret)
  • Access Token
  • Access Token Secret

Make Sure you have saved the values of the above keys because these values would be required in the subsequent steps.

The first thing you need to do is create a directory for the server code.

So create a .json file and write the below code to initiate npm. You also need to create a JavaScript file, which is server.js.

Below is that code snippet:

mkdir server
cd server
npm init
touch server.js

Now, we will install the Twit package to ensure secure communication with the Twitter API. Now, we will initialize all the necessary modules inside the server.js file.

Then, create an Express app by writing the below code.

const express = require('express');
const Twitter = require('twit');
const app = express();
 
app.listen(3000, () => console.log('Server running'))

Remember those four values we have got in the above step, and we are going to apply the same values to the Twitter package as written in the code snippet below, which will help us in the authentication process.

const api-client = new Twitter({
  consumer_key: 'CONSUMER_KEY',
  consumer_secret: 'CONSUMER_SECRET',
  access_token: 'ACCESS_TOKEN',
  access_token_secret: 'ACCESS_TOKEN_SECRET'
});

Please note that and the values which we are using as the keys in the above code snippet would be unique for all the applications.

When you created the Twitter application account, the account will assign unique keys.

Now, we will create endpoints for posting and retrieving the values from the server node.

GET statuses/home_timeline—shows the newest tweet uploaded by the users
GET statuses/home_timeline—shows tweets where the user is mentioned
POST statuses/update—it is used for sharing tweets

Now we will write the code to retrieve the tweets.

The first endpoint would be used for retrieving tweets on your timeline. Please note that we are able to write the number of tweets that we want to retrieve.

app.get('/home_timeline', (req, res) => {
    const params = { tweet_mode: 'extended', count: 10 };
   
    client
      .get(`statuses/home_timeline`, params)
      .then(timeline => {
         
        res.send(timeline);
      })
      .catch(error => {
      res.send(error);
    });
      
});

Now, with the below snippet, only those tweets will be shown where the user is mentioned.

app.get('/mentions_timeline', (req, res) => {
    const params = { tweet_mode: 'extended', count: 10 };
   
    client
      .get(`statuses/mentions_timeline`, params)
      .then(timeline => {
       
        res.send(timeline);
      })
      .catch(error => {
      res.send(error);
    });
      
});

Please note that we are not allowed to write anything on the Twitter timeline. To do that, we just need to change the value of Access permission to Read and Write.
SS1.png

In the above code snippet, we are enabling the capability to share tweets.

This code will be written on the server.js file to call the Twitter API to do the task.

app.post('/post_tweet', (req, res) => {
 
  tweet = req.body;
   
    client
      .post(`statuses/update`, tweet)
      .then(tweeting => {
        console.log(tweeting);
         
        res.send(tweeting);
      })
 
     .catch(error => {
      res.send(error);
    });
       
    
});

Now, you can go ahead and test the REST API along with Postman to make sure all the things are working perfectly fine.

So far, we have built the Node server and written foundational code to enable basic capabilities. Let’s move to the next step.

Step 3: Testing the Backend

This is important to ensure the backend is behaving as per our anticipation.

If anything goes wrong compared to what we’ve mentioned below, you might have to change your code to make it correct. Any AngularJS Web Application Development Company would advise you to give importance to this aspect.

Enter the query home_timeline. As soon as you do that, make sure you are getting something like below.
SS2.pngHere is the result of the GET request for the mentions_timeline endpoints.SS3.pngMake sure you are also working on the Twitter bot for maximum portability. You can use the below code to create a Twitter bot for yourself.

const express = require('express');
const Twitter = require('twit');
 
const app = express();
const client = new Twitter({
  consumer_key: 'Consumer Key Here',
  consumer_secret: 'Consumer Secret Here',
  access_token: 'Access Token Here',
  access_token_secret: 'Token Secret Here'
});
 
app.use(require('cors')());
app.use(require('body-parser').json());
 
app.post('/post_tweet', (req, res) => {
 
  tweet = {status:"Hello world"};
     
    client
      .post(`statuses/update`, tweet)
      .then(timeline => {
        console.log(timeline);
         
        res.send(timeline);
      })
 
     .catch(error => {
      res.send(error);
    });
          
});
 
app.listen(3000, () => console.log('Server running'));

Step 4: Develop an Independent Angular App to Leverage the REST APIs

This is one of the crucial steps of the whole process.

Here, we are going to work on AngularJS to build a unique and basic app to conserve the REST APIs from the Node server, which we had created in the beginning.

So, create an angular app by writing the below code.

ng new client

Now, you will need to work with the Node server from where we can request data.

To do that, we will need to tell services that would be in constant connection with the Node server.

Inside the Angular application, write the below code.

ng generate service twitterservice

Now we need to declare endpoints and inject the HttpClient inside the constructor. This whole process would be done inside a single file.

So, we would be creating two files, namely twitter.service.spec.ts and twitter.service.ts.

We would edit the file twitter.service.ts by adding the required imports and all the other changes mentioned in the above paragraph.

api_url = 'https://localhost:3000';
  
  constructor(private http: HttpClient) { }

To consume the REST API, we will write the below function.

export class TwitterService {
 
 api_url = 'http://localhost:3000';
  
  constructor(private http: HttpClient) { }
 
  getTimeline() {
    return this.http
      .get<any[]>(this.api_url+'/home_timeline')
      .pipe(map(data => data));
 
  }
 
  getMentions() {
    return this.http
      .get<any[]>(this.api_url+'/mentions_timeline')
      .pipe(map(data => data));
 
  }
 
}

After accessing the Twitter services, we will create two components below to do the job.

ng generate component twitter_timeline
ng generate component twitter_mentions
ng generate component tweet

Keep in mind that we have generated these components inside the app.module.ts. Now, we will declare the roots.

import { RouterModule, Routes } from '@angular/router';
 
const appRoutes: Routes = [
  {
    path: 'twitter_timeline',
    component: TwitterTimelineComponent
  },
  {
    path: 'twitter_mentions',
    component: TwitterMentionsComponent
  },
 
  {
    path: 'tweets',
    component: TweetComponent
  },
 
  { path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];

Now, render the component like below by going to app.component.html.

<mat-toolbar color="primary">
   <mat-toolbar-row>
     <!-- <span>HOME</span> -->
      <span><a href="/">HOME</a></span>
      <span class="spacer"></span>
      <span mat-button routerLink="/twitter_timeline">Timeline</span>
      <br>
      <a mat-button routerLink="/twitter_mentions">Mentions</a>
      <br>
      <a mat-button routerLink="/tweets">Tweets</a>
   </mat-toolbar-row>
</mat-toolbar>
<router-outlet></router-outlet>

Step 5: Retrieving Tweets

In this step, we’ll be aiming to get the tweets for further use. So, we would be creating components to display those tweets.

In this example, we are creating components TwitterTimelineComponent and TwitterMentionsComponent for specific purposes.

The TwitterTimelineComponent will retrieve all the recent tweets of the users who have authenticated the app.

The other component, TwitterMentionComponent, will be used to retrieve only those tweets which have a mention of the authenticated user.

First of all, go to twitter-timeline.component.ts and start working on TwitterTimelineComponent.

export class TwitterTimelineComponent implements OnInit {
   
  myTimeline: any;
 
  constructor(private api: TwitterService) { }
 
  ngOnInit() {
   this.getTwitterTimeline();
  }
   
  getTwitterTimeline(): void {
    this.api.getTimeline()
      .subscribe(
        myTimeline => {
          this.myTimeline = myTimeline;
          console.log(this.myTimeline);
        }
      )
   }
   
}

Please note that TwitterService inside the getTwitterTimeline method to pull data of the profile of the authenticated user.

Now, we would update twitter-timeline.component.html, as shown below.

<h1>Tweeter Timeline</h1>
<div *ngIf="undefined === myData">Loading...</div>
<div *ngIf="undefined !== myData">
  <div class ="card">
    <ng-container *ngFor="let tweets of myData.data">
      <h3>{{tweets.full_text
        }}
      </h3>
      <p>{{tweets.created_at}}</p>
      <p>{{tweets.user.name}}</p>
      <p>{{tweets.user.screen_name}}</p>
      <p>{{tweets.user.location}}</p>
      <p>{{tweets.user.description}}</p>
    </ng-container>
  </div>
</div>

After these steps, make sure you run your application. I’m sure you would get all the details of your tweets as soon as you run the app.

Step 6: Posting the Tweets

We are going to post the tweets from the /post_tweet endpoint. We will create a form that users will have to fill and click on submit the button at the end.

We are going to define the input types to restrict any inaccuracy for our task.

Go to tweet.component.ts and add the following code.

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
 
export class TweetComponent implements OnInit {
tweetForm: FormGroup;
    
  constructor(private api: TwitterService private formBuilder: FormBuilder) { }
 
  ngOnInit() {
 
   this.tweetForm = this.formBuilder.group({
            tweetdata: ['', Validators.required]
        });
  }
 
}

We are going to use the FormBuilder module to create the status update form.

Now just update the template so that Angular would know which form to use.

<mat-card class="contact-card">
  <mat-card-content>
    <form [formGroup]="tweetForm" (ngSubmit)="onSubmit()">
    <mat-form-field>
      <input matInput placeholder="Status" formControlName="tweetdata" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.tweetdata.errors }" >
    </mat-form-field>
    <br>
    <div class="form-group">
      <button [disabled]="loading" class="btn btn-primary">TWEET</button>
      <img *ngIf="loading" src="https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif" />
    </div>
    </form>
  </mat-card-content>
</mat-card>

You might have observed from the above code snippet, we have added the validators because we don’t want users to submit a blank form.

All we have to do is go to Twitter service and update The file by writing the below code.

  tweet(tweetdata: string) {
        return this.http.post<any>(`${this.api_url}/post_tweet/`, { status: tweetdata})
            .pipe(map(tweet => {
             
                alert("tweet posted")
 
                return tweet;
            }));
    }
 
}

This is going to call the API for posting to Twitter.

Now, we will update the TweetComponent, so go to tweet.component.ts and update the code as below.

export class TweetComponent implements OnInit {
tweetForm: FormGroup;
    loading = false;
    submitted = false;
    returnUrl: string;
    error = '';
 
  constructor(private api: TwitterService private formBuilder: FormBuilder) { }
 
  ngOnInit() {
 
   this.tweetForm = this.formBuilder.group({
            tweetdata: ['', Validators.required]
        });
  }
 
  get f() { return this.tweetForm.controls; }
 
    onSubmit() {
        this.submitted = true;
 
        // stop here if form is invalid
        if (this.tweetForm.invalid) {
            return;
        }
 
        this.loading = true;
        this.api.tweet(this.f.tweetdata.value)
            .pipe(first())
            .subscribe(
                data => {
                    console.log("yes")
                },
                error => {
                    this.error = error;
                    this.loading = false;
                });
    }
 
}

Now, to get all the latest tweets, all you have got to do is hit the /home_timeline endpoint. To get all the mentions, you need to go to /mentions_timeline endpoint and go to /post_tweet for the required purpose.

Wednesday, August 25, 2021

'moment-timezone'. CommonJS or AMD dependencies can cause optimization bailouts.

 Solution:

Add this code angular.json

"tsConfig": "tsconfig.app.json",

 "allowedCommonJsDependencies": [  "moment-timezone"],





Sunday, August 8, 2021

How to Sort an Array Alphabetically in JavaScript | Example | Demo

 we will look at sorting an array alphabetically in JavaScript. We will cover both arrays with strings and arrays with objects. and check with Demo.

1. Sorting an Array with Strings
2. Sorting an Array With Local Compare
3. Sorting an Array With Local compare Object

Demo Link


Example Sort Array



Angular Searchable Dropdown | Demo | Example

 

Filter/search from the drop-down list of options using angular


I have multi-select drop-down with check-boxes and a drop-down list options. I wanted to implement an run time/dynamic filtered search for the drop-down options. I was able to implement filtered search but not that at run time. 

Angular 12 Searchable Drop Down also you can check demo. angular is very easy to use for searchable drop down.

Angular is one of the most popular JavaScript frameworks out there, notably with enterprise systems. In this article, you’ll learn how to create a custom searchable dropdown component which can search through an array of data and return the particular item a user searches for.
At the end of this article, you’ll create a real-world custom search component which searches for your favorite TV shows and displays some information about it to you.

Demo Link

Angular Searchable Dropdown Demo:



Wednesday, August 4, 2021

What is CSS

 CSS is the language we use to style an HTML document.

CSS describes how HTML elements should be displayed.

This tutorial will teach you CSS from basic to advanced.

What is Javascript

 JavaScript is the best  world's most popular programming language.

JavaScript is  the programming language of the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.

Friday, July 30, 2021

How to validate only gmail in Angular Reactive Form | Example


Angular Reactive Form Validate Only Gmail

You can Easy Validate Email in Angular Reactive Form Below Given code use and It will be help you for you needed. 

 this.testForm=this.formBuilder.group({

      email:['', [Validators.required, Validators.email, Validators.pattern('^.+@gmail.com$')]],

})

Wednesday, July 7, 2021

TypeScript - Classes - Example - Demo

TypeScript - Classes

Typescript Javascript Classes is object-oriented programming languages like Java and C#, classes are the fundamental entities used to create reusable components. Functionalities are passed down to classes and objects are created from classes. However, until ECMAScript 6 (also known as ECMAScript 2015), this was not the case with JavaScript. JavaScript has been primarily a functional programming language where inheritance is prototype-based. Functions are used to build reusable components. In ECMAScript 6, object-oriented class based approach was introduced. TypeScript introduced classes to avail the benefit of object-oriented techniques like encapsulation and abstraction. The class in TypeScript is compiled to plain JavaScript functions by the TypeScript compiler to work across platforms and browsers.

A class can include the following:
Constructor
Properties
Methods



Typesript Classes Example Below






Sunday, July 4, 2021

TypeScript - Interfaces | Example | demo

TypeScript - Interfaces

 
Interface is a structure that defines the contract in your application. It defines the syntax for classes to follow. Classes that are derived from an interface must follow the structure provided by their interface.
 
The TypeScript compiler does not convert interface to JavaScript. It uses interface for type checking. This is also known as "duck typing" or "structural subtyping".
An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function.

1.Interface as Function Type

2.Interface for Array Type

3.Optional Property

4.Read only Properties


You can see all Example Interface Below Demo








TypeScript - Rest Parameters | Example | Demo

TypeScript - Rest Parameters

Typescript Rest Parametes you learned about functions and their parameters. TypeScript introduced rest parameters to accommodate n number of parameters easily.


When the number of parameters that a function will receive is not known or can vary, we can use rest parameters. In JavaScript, this is achieved with the "arguments" variable. However, with TypeScript, we can use the rest parameter denoted by ellipsis ....


We can pass zero or more arguments to the rest parameter. The compiler will create an array of arguments with the rest parameter name provided by us.





Rest Parameters Example







Demo Rest Parameters



TypeScript - Function Overloading | Example | Demo

TypeScript - Function Overloading



TypeScript Function Overloading witch can realy help to overloading function and make good function provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.


The last function should have the function implementation. Since the return type can be either string or number as per the first two function declarations, we must use compatible parameters and return type as any in the function definition.
Function overloading with different number of parameters and types with same name is not supported

Function Overloading Example Below










Function Overloading Demo

TypeScript - Arrow Functions | Example | Demo

TypeScript - Arrow Functions

The Typescipt Arrow Function is very Import function is ES6 with the arrow function help make gootd coding Fat arrow witch notations are used for anonymous functions i.e for function expressions. They are also called lambda functions in other languages.


The Typescirpt Arrow Function Using fat arrow =>, we dropped the need to use the function keyword. Parameters are passed in the parenthesis (), and the function expression is enclosed within the curly brackets { }.





The Below Give Example Typescript Arrow Function witch can help you for Leanring









Arrow Function Example



TypeScript - Functions | Example | Demo

TypeScript - Functions

The Typescript Functions are the primary blocks of any program. In JavaScript, functions are the most important part since the JavaScript is a functional programming language. With functions, you can implement/mimic the concepts of object-oriented programming like classes, objects, polymorphism, and, abstraction.
 
The Typescript Functions ensure that the program is maintainable and reusable, and organized into readable blocks. While TypeScript provides the concept of classes and modules, functions still are an integral part of the language.


The given below Example you can see how to work Typscript Function









Demo Typscript Function



TypeScript - while Loop | Example | Demo

TypeScript - while Loop
The Typescript while loop is another type of loop that checks for a specified condition before beginning to execute the block of statements. The loop runs until the condition value is met.


The below given Example While loop checking condition







Demo




TypeScript - for Loops | Example | Demo

TypeScript - for Loops TypeScript is types following types below:
1. for loop
2 . for..of loop
3 for..in loop

Let's take Demo For Loop



Example For Typescript Loops

Saturday, July 3, 2021

TypeScript - Switch - Example - Demo

TypeScript - Switch - Example - Demo




Type Script Using Switch Example. The switch statement is used to check for multiple values and executes sets of statements for each of those values. A switch statement has one block of code corresponding to each value and can have any number of such blocks. When the match to a value is found, the corresponding block of code is executed.


Example Demo





DEMO



Friday, July 2, 2021

TypeScript - if else | Example | Demo

Here you will be leanr Typescript If Else condition. An if statement can include one or more expressions which return boolean. If the boolean expression evaluates to true, a set of statements is then executed.



Example





Demo If Else


Thursday, July 1, 2021

Type Assertion in TypeScript | Example | Demo

Here, you will learn about how TypeScript infers and checks the type of a variable using some internal logic mechanism called Type Assertion.
Type assertion allows you to set the type of a value and tell the compiler not to infer it. This is when you, as a programmer, might have a better understanding of the type of a variable than what TypeScript can infer on its own. Such a situation can occur when you might be porting over code from JavaScript and you may know a more accurate type of the variable than what is currently assigned. It is similar to type casting in other languages like C# and Java. However, unlike C# and Java, there is no runtime effect of type assertion in TypeScript. It is merely a way to let the TypeScript compiler know the type of a variable.


Example Here






Demo

Assertion Demo


Type Inference in TypeScript | Example | Demo

Type Inference in TypeScript
TypeScript is a typed language. However, it is not mandatory to specify the type of a variable. TypeScript infers types of variables when there is no explicit information available in the form of type annotations.
Types are inferred by TypeScript compiler when:
1. Variables are initialized
2. Default values are set for parameters
3. Function return types are determined

Example



Demo


Demo Inference

TypeScript Data Type - Never | Example | Demo

TypeScript Data Type - Never
TypeScript introduced a new type never, which indicates the values that will never occur.
The never type is used when you are sure that something is never going to occur. For example, you write a function which will not return to its end point or always throws an exception.


Example





Demo


Demo

TypeScript Data Type - Void | Example | Demo

TypeScript Data Type - Void

Similar to languages like Java, void is used where there is no data. For example, if a function does not return any value then you can specify void as return type.

Example





Demo:


Demo

TypeScript Data Type - Any | Example | Demo

TypeScript Data Type - Any


TypeScript has type-checking and compile-time checks. However, we do not always have prior knowledge about the type of some variables, especially when there are user-entered values from third party libraries. In such cases, we need a provision that can deal with dynamic content. The Any type comes in handy here.

Example



Demo


Demo

TypeScript - Union | Example | Demo

TypeScript - Union


TypeScript allows us to use more than one data type for a variable or a function parameter. This is called union type.

Example




Demo

Demo

TypeScript Data Type - Enum | Example | Demo

TypeScript Data Type - Enum


Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too.
In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.
There are three types of enums:
1. Numeric enum
2. String enum
3 Heterogeneous enum

1. Numeric Enum

Numeric enums are number-based enums i.e. they store string values as numbers. Enums can be defined using the keyword enum. Let's say we want to store a set of print media types. The corresponding enum in TypeScript would be:
2 String Enum
String enums are similar to numeric enums, except that the enum values are initialized with string values rather than numeric values.
The benefits of using string enums is that string enums offer better readability. If we were to debug a program, it is easier to read string values rather than numeric values.
3 Heterogeneous Enum
Heterogeneous enums are enums that contain both string and numeric values.

Example



Demo

Demo

TypeScript - Tuples | Example | Demo

TypeScript - Tuples


TypeScript introduced a new data type called Tuple. Tuple can contain two values of different data types.
Consider the following example of number, string and tuple type variables.

Example | Demo



Demo: Demo

TypeScript - Arrays | Example | Demo

An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax.
TypeScript supports arrays, similar to JavaScript. There are two ways to declare an array:

Array Methods
Method Description
pop() Removes the last element of the array and return that element
push() Adds new elements to the array and returns the new array length
sort() Sorts all the elements of the array
concat() Joins two arrays and returns the combined result
indexOf() Returns the index of the first match of a value in the array (-1 if not found)
copyWithin() Copies a sequence of elements within the array
fill() Fills the array with a static value from the provided start index to the end index
shift() Removes and returns the first element of the array
splice() Adds or removes elements from the array
unshift() Adds one or more elements to the beginning of the array
includes() Checks whether the array contains a certain element
join() Joins all elements of the array into a string
lastIndexOf() Returns the last index of an element in the array
slice() Extracts a section of the array and returns the new array
toString() Returns a string representation of the array
toLocaleString() Returns a localized string representing the array


Demo Example





TypeScript Data Type - Boolean | Example | Demo

Boolean values are supported by both JavaScript and TypeScript and stored as true/false values.

TypeScript Boolean:

let isOn:boolean = true; let isOff:boolean = true;

Note that, Boolean with an upper case B is different from boolean with a lower case b. Upper case Boolean is an object type whereas lower case boolean is a primitive type. It is always recommended to use boolean, the primitive type in your programs. This is because, while JavaScript coerces an object to its primitive type, the TypeScript type system does not. TypeScript treats it like an object type.

Demo | Example





How to build an Express and Node.js app with Typescript

  In this tutorial, you will learn how to set up a Node.js and Express project with Typescript and live auto-reloading. Note that this metho...