Class field constructor function TypeScript

How to create fields, constructor and function in TypeScript Class?

What is class in TypeScript?

A class is a template definition of the methods and variables in a particular kind of object. It is extensible program, code and template for creating objects.

A TypeScript is object oriented JavaScript and it also supports object oriented programming features like classes, interfaces, etc.


A class captains the Public, Private, Protected and Read-only modifiers and Public by default.
You can see the below example, the class User and each members are public by default.


A class definition can contains the following –
1.     Fields
2.     Constructors
3.     Functions

Example – Use of class field, constructor and function i.e.
//Example 1- A simple class based example.
class User { // Calss
    name: string; //field
    constructor(nameTxt: string) { //constructor
        this.name = nameTxt;
    }

    getName() {//function
        return "Hello, " + this.name;
    }
}

let user = new User("Anil");//Creating Instance objects

How Static class in typescript?
We can define a class with static properties i.e.

export class Constants {
    static baseUrl = 'http://localhost:8080/';
    static date = new Date();
}

Ways to declare a nest class structure in typescript?

//Example 1-
declare module a{

    class b {
    }

    module b {
        class c {
        }
    }
}

var clB = new a.b();
var clC = new a.b.c();

//Example 2-
export module a {
    export class b {
    }

    export module b {
        export enum c {
            C1 = 1,
            C2 = 2,
            C3 = 3,
        }
    }
}

//Example 3-
class A {
    static B = class { }
}

var a = new A();
var b = new A.B();

Stayed Informed – Learn Angular 2 with TypeScript

I hope you are enjoying with this post! Please share with you friends. Thank you!!

ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book