Home PC Games Linux Windows Database Network Programming Server Mobile  
           
  Home \ Programming \ TypeScript basic grammar     - Linux directory structure (Linux)

- Go Languages Reviews (Programming)

- GAMIT10.5 under CentOS installation (Linux)

- Understanding the type in C ++ bitset (Programming)

- Json data with double backslashes to a single backslash Json data processing (Programming)

- GitLab remote backup of Linux Shell Scripting (Linux)

- Safety testing Unix and Linux server entry succinctly (Linux)

- Linux module mechanism of (Programming)

- Docker startups use continuous integration deployment (Server)

- Linux initialization init systems - Systemd (Linux)

- Manually generate AWR reports (Database)

- HAproxy let IP recording back-end RS (Server)

- Source code to compile and install MySQL 5.7.9 (Database)

- How UTorrent download the ISO image from the command line (Linux)

- HTTP and FTP TCP-FLOOD CC Attacks Analysis and Prevention solutions under CentOS 6.5 (Linux)

- Build their own recursive DNS server (Server)

- Hadoop2.0 configuration yarn success (Server)

- Security matters and practical Linux System (Linux)

- The method of installing software under Ubuntu Linux (Linux)

- How to clear the DNS query cache under Linux / Unix / Mac (Linux)

 
         
  TypeScript basic grammar
     
  Add Date : 2018-11-21      
         
         
         
  TypeScript was developed by Microsoft superset of JavaScript, TypeScript compatible with JavaScript, JavaScript code can be loaded and run. TypeScript compared with local JavaScript Progress comprising: adding comments to make the compiler support objects and understand the function, the compiler will remove comments without increasing overhead; add a complete class structure, so that it is traditional for the update object language.

TypeScript Microsoft's official website http://www.typescriptlang.org/
TypeScript source http://typescript.codeplex.com

1. Basic Data Types

Boolean

// Boolean
var isDone: boolean = false;
Number

// Number
var width: number = 100;
String

// String
var name: string = "hello";
Array

// Array
var list: number [] = [1, 2, 3];
var list: Array < number> = [1, 2, 3];
Enum

// Enum
enum Color {Red, Green, Blue}
var c: Color = Color.Red;
alert (c); // default index starts at 0, alert (0);
// You can specify index manually
enum Color1 {Red = 1, Green, Blue}
var c1: Color1 = Color1.Green;
alert (c1); // alert (2)
// Find the name according to the subscript
enum Color2 {Red = 1, Green = 2, Blue = 4}
var c2: string = Color2 [4];
alert (c2); // alert (Blue)
Any

// Unsure, exit compile inspection
var notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

// Sure array element type
var anylist: any [] = [1, true, "free"];
anylist [1] = 100;
Void

//blank
function warnUser (): void {
    alert (123);
}
2. Class

The basic syntax

class Animal {
    animalName: string;

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

    sayHello () {
        alert (this.animalName + ": Hello");
    }
}

var tom = new Animal ( "Tom");
tom.sayHello (); // alert (Tom: Hello)
inherit

class Animal {
    animalName: string;

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

    sayHello () {
        alert (this.animalName + ": Hello");
    }
}

class Cat extends Animal {
    // Rewrite sayHello method
    sayHello () {
        alert (this.animalName + "(Cat):" + "Hello");
    }
}

class Mouse extends Animal {
    sayHello () {
        alert (this.animalName + "(Mouse):" + "Hello");
    }
}

var tom: Animal = new Cat ( "Tom");
tom.sayHello (); // alert (Tom (Cat): Hello)
var jerry: Animal = new Mouse ( "Jerry");
jerry.sayHello (); // alert (Jerry (Mouse): Hello)
Modifiers

When we changed to private animalName

class Animal {
    private animalName: string; // default is public

    constructor (name: string) {
        this.animalName = name;
    }
    // ...
}

class Cat extends Animal {
    // Rewrite sayHello method
    sayHello () {
        alert (this.animalName + "(Cat):" + "Hello"); // Error compiler does not pass
    }
}
get, set accessor

class Animal {
    private _animalName: string; // default is public

    get animalName (): string {
        return this._animalName;
    }

    set animalName (name: string): string {
        this._animalName = name;
    }

    // ...
}
Static properties

// Static properties
class Table {
    static width = 100;
    static height = 200;
}

var width = Table.width;
alert (width); // alert (100)
3. Interface

The basic syntax

interface ICar {
    color: string;
}

class Bus implements ICar {
    color: string;
    constructor () {
        this.color = "Blue";
    }
}

var bus = new Bus ();
alert (bus.color);
Inherited Interface

// Inheritance Interface
interface Shape {
    color: string;
}

interface PenStroke {
    penWidth: number;
}

interface Square extends Shape, PenStroke {
    sideLength: number;
}
Optional attributes

interface ICar {
    color: string;
    ? SafetyDevice: any; // implementation class does not implement
}

function MoveCar (car: ICar) {
    if (car.safetyDevice)
    {
        alert ( "The car is safe");
    }
    else
    {
        alert ( "The car is not safe");
    }
}

4. The module (Modules)

Role: 1 to prevent namespace conflicts; 2 function modules can be easily divided into different files easier to maintain;.

The basic syntax

module MyDemo {
    export interface IDemo {

    }

    export class Demo implements IDemo {

    }
}
Aliases

module Shapes {
    export module Polygons {
        export class Triangle {}
        export class Square {}
    }
}

import polygons = Shapes.Polygons;
var sq = new polygons.Square (); // similar to the 'new Shapes.Polygons.Square ()'
5. Function (Function)

The basic syntax

function add (x: number, y: number): number {
    return x + y;
}
// Or
var myAdd = function (x: number, y: number): number {
    return x + y;
};
Full function type

var myAdd: (x: number, y: number) => number =
    function (x: number, y: number): number {
        return x + y;
    };
To enhance readability, to the parameter x, y has practical significance, can be written

var myAdd: (baseValue: number, increment: number) => number =
    function (x: number, y: number): number {
        return x + y;
    };
The second part number is a return type, if without the return type, use the 'void'
The third part of the type of function parameters, depending on the context type inference can be omitted

var myAdd: (baseValue: number, increment: number) => number =
    function (x, y) {
        return x + y;
    };
Optional parameters

// Optional parameter
function buildName (firstName: string, lastName:? string) {
    if (lastName)
        return firstName + "" + lastName;
    else return firstName;
}
var result1 = buildName ( "Bob");
The default parameters

// Default parameters
function buildNameDefaultValue (firstName: string, lastName = "Smith") {
        return firstName + "" + lastName;
}
var result1 = buildNameDefaultValue ( "Bob");
Variable parameter

For example, in C #, method parameters are defined using the param int [], when calling the method, you can pass multiple parameters of type int
In the TypeScript

function buildNameRest (firstName: string, ... restOfName: string []) {
    return firstName + "" + restOfName.join ( "");
}

var employeeName = buildNameRest ( "Joseph", "Samuel", "Lucas", "MacKinzie")
Lambads and this keyword

var people = {
    name: [ "Joe Smith", "John Doe", "Wang five", "Zhao six"],
    getName: function () {
        return function () {
            var i = Math.floor (Math.random () * 4);
            return {
                n: this.name [i]
            }
        }
    }
}

var pname = people.getName ();
alert ( "name:" + pname () n.);
Call getName found in this key point is getName, less than the external access attribute name
So we revised as follows:

var people = {
    name: [ "Joe Smith", "John Doe", "Wang five", "Zhao six"],
    getName: function () {
        return () => {
            var i = Math.floor (Math.random () * 4);
            return {
                n: this.name [i]
            }
        }
    }
}

var pname = people.getName ();
alert ( "name:" + pname () n.);
Overloaded

// Overload
function student (name: string): string;
function student (age: number): number;
function student (numberorage: any): any {
    if (numberorage && typeof (numberorage) == "string")
        alert ( "name");
    else
        alert ( "Age");
}
student ( "Tom"); // alert ( "name")
student (15); // alert ( "Age")

5. Generics

The basic syntax

Generic type (generic function type)

Generic Interface

Generic class

class GenericNumber < T> {
    zeroValue: T;
    add: (x: T, y: T) => T;
}

var myGenericNumber = new GenericNumber < number> ();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
    return x + y;
};

function identity < T> (arg: T): T {
    return arg;
}

// Array of generics
function identity < T> (arg: T []): T [] {
    console.log (arg.length);
}

function identity < T> (arg: T): T {
    return arg;
}
var myIdentity: < T> (arg: T) => T = identity; // T may also be used other letters
// Can also write
// Var myIdentity: {< T> (arg: T): T} = identity;

interface GenericIdentityFn {
    < T> (arg: T): T;
}

function identity < T> (arg: T): T {
    return arg;
}

var myIdentity: GenericIdentityFn = identity;

Generic constraints

interface Lengthwise {
    length: number;
}

function loggingIdentity < T extends Lengthwise> (arg: T): T {
    console.log (arg.length);
    return arg;
}

loggingIdentity (3); // error
loggingIdentity ({length: 10, value: 3}); // Just type attribute to contain length
Generic class constraint

class Findable < T>
{
    // ...
}
function find < T> (n: T, s: Findable < T>) {
    // ...
}

6. Merge

Merge Interface

interface Box {
    height: number;
    width: number;
}

interface Box {
    scale: number;
}

var box: Box = {height: 5, width: 6, scale: 10};
Merge Modules

module Animals {
    exportclass Zebra {}
}

module Animals {
    exportinterface Legged {numberOfLegs: number;}
    exportclass Dog {}
}

// Equivalent
module Animals {
    exportinterface Legged {numberOfLegs: number;}
    
    exportclass Zebra {}
    exportclass Dog {}
}

Merge modules and classes

class Album {
    label: Album.AlbumLabel;
}
module Album {
    export class AlbumLabel {
    }
}
Merge modules and functions

function buildLabel (name: string): string {
    return buildLabel.prefix + name + buildLabel.suffix;
}

module buildLabel {
    export var suffix = "";
    export var prefix = "Hello,";
}

alert (buildLabel ( "Sam Smith"));
Merge module enumeration

enum Color {
    red = 1,
    green = 2,
    blue = 4
}

module Color {
    export function mixColor (colorName: string) {
        if (colorName == "yellow") {
            return Color.red + Color.green;
        }
        else if (colorName == "white") {
            return Color.red + Color.green + Color.blue;
        }
        else if (colorName == "magenta") {
            return Color.red + Color.blue;
        }
        else if (colorName == "cyan") {
            return Color.green + Color.blue;
        }
    }
}
Can not be combined

Classes and class can not be combined
Interfaces and classes can not be combined
Variables can not be combined with class
     
         
         
         
  More:      
 
- Heartbeat cluster components Overview (Server)
- Using VMware vSphere Client Linux virtual machine installation CentOS6.4 system (Linux)
- Depth understanding of DB2 table space (Tablespace) (Database)
- Why you can have JavaScript string method (Programming)
- Linux user login and IP restrictions (Linux)
- Linux Command - ps: a snapshot of the current process (Linux)
- SQL Server memory Misunderstanding (Database)
- Linux, Oracle listen address modification (Database)
- Those things packaged using Gradle to Android (Programming)
- How to upgrade Docker 1.6 on Fedora / CentOS (Server)
- Redis is installed and set up Ubuntu 14.04 from the environment under the main ssdb (Server)
- Install the open source database PostgreSQL 9.4 and phpMyAdmin on Ubuntu (Database)
- To update Python version under CentOS system (Linux)
- To modify the existing user ID and comments GPG key (Linux)
- An Analysis of the C Algorithm for Calculating the Number of Days Between Date (Programming)
- How to ensure the Linux SSH login security with one-time password (Linux)
- CentOS environment prepared crontab scheduled tasks (Linux)
- Linux kernel update error, update-initramfs: failed Solution (Linux)
- Forgot Linux root password (Linux)
- Use FFmpeg processing high quality GIF (Programming)
     
           
     
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.