Introduction to TypeScript

Keywords: Web Development TypeScript Javascript npm ECMAScript

Introduction to TypeScript

Before using TypeScript, we need:

Installing TypeScript uses nmp-v to check whether npm is installed

Use tsc-v to check whether the TypeScript environment is installed or not, use NPM install-g type script installation environment, use tsc test.ts to mutate the TypeScript.ts file into JavaScript.js file. TypeScript itself is based on JavaScript, so summarize some commonly used content highlighting TypeScript.

Basic types:

boolean value: boolean

 let isDone:boolean=false

console.log(isDone)// false

Numbers: Like JavaScript, all numbers in TypeScript are floating-point numbers. The type of these floating-point numbers is number. In addition to supporting decimal and hexadecimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015.

let decLiteral: number = 6; //6

let hexLiteral: number = 0xf00d;  // 61453

let binaryLiteral: number = 0b1010; //10

let octalLiteral: number = 0o744; //484

String

let name: string = "bob";

name = "smith";
let sentence: string = `Hello, 
                        my name is
                        ${ name }.`

array

let list: number[] = [1, 2, 3];

The second way is to use array generics, Array <Element Type>:

let list: Array<number> = [1, 2, 3]

Tuple Tuple

let x: [string, number];

x = ['hello', 10]; // OK

console.log(x[0].substr(1))

x[3]='Character string'// Use joint substitution when crossing the border as long as it can be the type where x already exists

//x[4]=true; // Error reporting is compiled to js and works, but don't write like this

console.log(x)

enumeration

enum Color {Red, Green, Blue,red=8}//The default is to assign from 0 or manually.

let c: Color = Color.Green//c: 1

console.log(Color[2]) //If you want to get the corresponding value

console.log(Color[Color.Green]) //Or so

Any

It allows you to optionally include or remove type checks at compilation time, as if I don't know what type it is for the time being.

It's a bit like Object.

var list = [1, true, "free",false];  

list[1] = "111";  //The original true is now allowed to be changed to strings as well.

console.log(list);

void

Represents that no return value is often seen in functions and methods, which is of little use because you can only assign undefined and null to it.

function warnUser(): void {

}

let unusable: void = undefined;

console.log(unusable)

Null and Undefined

By default null and undefined are subtypes of all types. That is, you can assign null and undefined to variables of type number.

let u: undefined = undefined;

let n: null = null;

const num:number =null;

const str:string=undefined;

Naver

The never type represents the types of values that never exist.

The never type is a subtype of any type and can be assigned to any type; however, no type is a subtype of the never or can be assigned to the never type (except for the never itself). Even any cannot be assigned to never. ,

Class and inheritance and permission modifiers

Class declares classes, extends declares inheritance classes

The subclass contains a constructor that must call super()

inherit

class Person{

    name: string;

    constructor(name="Anonymous person"){

        this.name=name;

    }

    speak(){

        console.log(`My name is: ${this.name}`)

    }

}

class Steudent extends Person{

    constructor(name) {

        super(name); //Name points to the name of the parent class 

    }

}

const  sut1=new Steudent("Mao"); //So if this parameter is changed to undefined, it will
//Anonymous with the default value of the parent class

sut1.speak();
//---------------------------------------------------------------------

class  Atou extends Person{ //After inheritance, even if nothing is written, the method of the parent class will be inherited.

    speak(){

        console.log(`Atou The name is: ${this.name}`)

    }

}



const  atao=new Atou("Ataos")

atao.speak();

Permission modifier:

private: private access is limited to this class

public: public defaults are accessible

Protected: protected classes and their subclasses

Accessor: Intercept access to object members through getters/setters.

class Person{

    constructor(){



    }

    private  _name="Default name";//Give a default value

  public  get name(){

        return this._name;

    }

   public set name(name){

       this._name=name;

    }

}

const  p=new Person();

console.log(p.name) //Default name

p.name="Revised name"   //Here we can make amendments and pass them.

console.log(p.name) //Modified name
 

Abstract classes (extracting common features, not instantiating, more object-oriented)

Abstract methods in abstract classes do not contain concrete implementations and must be implemented in derived classes. The syntax of abstract methods is similar to that of interface methods. Both define method signatures but do not contain method bodies. However, abstract methods must contain Abstract keywords and can contain access modifiers

var __extends = (this && this.__extends) || (function () {

    var extendStatics = function (d, b) {

        extendStatics = Object.setPrototypeOf ||

            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||

            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };

        return extendStatics(d, b);

    }

    return function (d, b) {

        extendStatics(d, b);

        function __() { this.constructor = d; }

        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());

    };

})();

var Department = /** @class */ (function () {

    function Department(name) {

        this.name = name;

    }

    Department.prototype.printName = function () {

        console.log('Department name: ' + this.name);

    };

    return Department;

}());

var AccountingDepartment = /** @class */ (function (_super) {

    __extends(AccountingDepartment, _super);

    function AccountingDepartment() {

        return _super.call(this, 'Accounting and Auditing') || this;

    }

    AccountingDepartment.prototype.printMeeting = function () {

        console.log('The Accounting Department meets each Monday at 10am.');

    };

    AccountingDepartment.prototype.generateReports = function () {

        console.log('Generating accounting reports...');

    };

    return AccountingDepartment;

}(Department));

var department; // Allow you to create a reference to an abstract type

// department = new Department(); // Error: An instance of an abstract class cannot be created

department = new AccountingDepartment(); // Allow instantiation and assignment of an abstract subclass

department.printName();

department.printMeeting();

//department.generateReports(); // Error: Method does not exist in declared abstract classes

Interface

The attributes in the interface are not all necessary, they can be selected according to their own needs, and a class can implement multiple interfaces.

Implementing interfaces using implements keywords

interface Persion{

    name,

    speak()

}

class Student implements Persion{

    name;

    speak() {

        return this.name;

    }

}

const s1 = new Student();

s1.name = "Zhang San"

console.log(s1.speak());

generic paradigm

function identity<T>(arg: T): T {

    return arg;

}

let output = identity<string>("myString");

Template

export  const name="Zhang San";

export   function square(x) {

    return x * x;

}

html:

<script type="module">

    import {name,square} from "./one.js";

    console.log(square(11));

    console.log(name)

    </script>

Some simple summaries of the above books, welcome messages where you need to add or question or mistake.

Posted by rcity on Tue, 29 Jan 2019 04:39:14 -0800