Introduce a,

TypeScript is a superset of JavaScript types that can be compiled into pure JavaScript.

TypeScript is an open source programming language developed by Microsoft. It is built by adding static type definitions on top of JavaScript. TypeScript is translated into JavaScript code by the TypeScript compiler or Babel and runs in any browser and operating system.

Second, the installation

npm install -g typescript

npm install -g ts-node

Three, advantage

  1. TypeScriptDon’t stopJavaScriptThe operation of the
  2. Editor prompt, there are error prompts in the development process, timely find potential problems
  3. Code readability, robustness, and maintainability are improved
  4. Application scenario: Components and interfaces transmit parameters or obtain data, avoiding less, more, or incorrect data transmission

Four, grammar,

4.1 Static Type

4.1.1 Basic Types

Base types: null, undefined, symbol, Boolean, void, number, string, never, any

// Base types: null, undefined, symbol, Boolean, void, number, string, any
let names: string = "jack";
let age: number = 13;
let flag: boolean = true;
let grade: void = undefined;

let x: any = 1;    // Number type
x = 'test';    // A string of characters
x = false;    // Boolean typeThe never type represents the types of values that never exist. For example, the never type is the return type of function expressions or arrow function expressions that always throw an exception or have no return value at all; Variables can also be of type never, when they are bound by type protection that is never true. The never type is a subtype of any type and can be assigned to any type; However, no type is a subtype of never or can be assigned to a type of never (except never itself). Even any cannot be assigned to never.// Base type :never

let y: never;
let z: number;

// Error running. The numeric type cannot be converted to never
y = 123;

// The never type can be assigned to the never type
y = (() = >{ throw new Error('exception')}) ();// A function that returns never can be the case where an exception is thrown
function error(message: string) :never {
    throw new Error(message);
}

// A function that returns never can be a terminating point that cannot be executed
function loop() :never {
    while (true) {}}Copy the code

4.1.2 Object Types

Object types: [], {}, Class, function

// Object types: [], {}, Class, function

class Person {}
const student: { name: string; age: number; } = { name: 'hua'.age: 18 };
const numbers: number[] = [1.2.3];
const strs: string[] = ['1'.'2'.'3'];
const xiaoming: Person = new Person();
const getTotal: () = > number = () = > {
    return 123;
};
Copy the code

4.1.3 tuples

Tuples: Tuples are used when the data types of the elements stored in an array are different

/ / array
const arr: (number | string)[] = [1.'2'.3];
const stringArr: string[] = ['a'.'b'.'c'];
const undefinedArr: undefined[] = [undefined];

/ / a tuple tuple
const teacherInfo: [string, string, number] = ['Dell'.'male'.18];
// csv
const teacherList: [string, string, number][] = [['dell'.'male'.19], ['sun'.'female'.26], ['jeny'.'female'.38]].Copy the code

4.2 Type annotation, type inference, and type assertion

4.2.1 Type annotation and type inference

Type annotations: Specify a type for a variable, and when you hover over the variable, the type annotations appear.

Type inference: TS can also infer what type variables are without adding type annotations, and deduce the types of variables backward according to their values.

// Type annotations and type inference
let count: number = 123;
let countInference = 123;

const firstNumber = 1;
const secondNumber = 2;
const total = firstNumber + secondNumber;

interface Person {
    name: 'string';
}
const rawData = '{"name": "xiaoming"}';
const newData: Person = JSON.parse(rawData);

let temp: number | string = 123;
temp = '456'; Function dependent type// Function related types
let temp: number | string = 123;
temp = '456';

function add(first: number, second: number) :number {
    return first + second;
}

function sayHello() :void {
    console.log('hello');
}

function errorEmitter() :never {
    while(true) {}}function add2({ first, second }: { first: number; second: number }) :number {
    return first + second;
}

function getNumber({ first }: { first: number }) {
    return first;
}

const total2 = add2({ first: 1.second: 2 });
const count2 = getNumber({ first: 1 });
Copy the code

4.2.2 Type Assertion

Type assertion: Select a type

// Type assertion
interface IDog {
    name: 'wang'.age: 1.bark: () = > { }
}

interface ICat {
    name: 'miao'.age: 1.miao: () = >{}}function func(animal: IDog | ICat) {
    if ((<IDog>animal).bark) {
        return (<IDog>animal).bark();
      } else {
        return(<ICat>animal).miao(); }}function func2(animal: IDog | ICat) {
    if (animal as IDog) {
        return (animal as IDog).bark();
    } else {
        return (animal asICat).miao(); }}Copy the code

4.3 Interface Alias of the Interface and Type

4.3.1 interface interface

Interface: Encapsulates parameters and defines data in an object format (interface and type are similar but not identical)

interface IPerson { 
    firstName:string, 
    lastName:string, 
    sayHi: () = >string 
} 
 
var customer:IPerson = { 
    firstName:"Tom".lastName:"Hanks".sayHi: (a) :string= >{return "Hi there"}} Interface inheritance: Typescript allows interfaces to inherit from multiple interfaces using keywordsextends

/ / inheritance
interface Person { 
    age:number 
 } 
  
interface XiaoMing extends Person { 
    interest: string 
}

// Multiple inheritance instances
interface IFather { 
    v1:number 
} 
 
interface IMonther { 
    v2:number 
} 
 
interface Child extends IFather, IMonther { }

#### 4.32.Type Alias: Encapsulates parameters and defines data without object format// Declare a type
type Alice = {
	name: string, age: number}// Use this type
const alice : Aclice = {
	name : 'Ming'.age : 18
}

type Name = string;
const name: Name = 'xiaoming';
Copy the code

4.3.3 Interface Alias Difference between interface and Type

Type can declare primitive type aliases, union types, tuples, and so on

The type statement can also be assigned to the typeof the instance obtained using typeof

// Base type alias
type Name = string

// Union type
interface Dog {
 wong();
}
interface Cat {
 miao();
}

type Pet = Dog | Cat

// Specify the type of each position in the array
type PetList = [Dog, Pet]


When you want to get the typeof a variable, use typeof
let div = document.createElement('div');
type B = typeof div
      3.Interface can declare merge interface User {name: string
 age: number
}

interface User {
 sex: string
}

/*
User 接口为 {
 name: string
 age: number
 sex: string 
}
*/
Copy the code

4.4 Association Type

Joint type (Union Types) : can be set through the pipe (|) variable multiple Types, assignment can be assigned according to the type of set

// Union type
var val:string|number 
val = 12 
console.log("The number is"+ val) 
val = "Runoob" 
console.log("String as" + val)


// case2
interface IFather { 
    v1:number 
} 
 
interface IMonther { 
    v2:number 
} 
const person:IFather | IMonther = {v1: 12};
Copy the code

4.5 Enum Enum type

Enumeration: A complement to the JS standard data type that declares a set of named constants

enum Status {
    OFFLINE = 1,
    ONLINE,
    DELETED
}

console.log(Status.OFFLINE, Status[0]);

// const Status = {
// OFFLINE: 0,
// ONLINE: 1,
// DELETED: 2
// }

// function getResult(status) {
// if (status === Status.OFFLINE) {
// return 'offline';
// } else if (status === Status.ONLINE) {
// return 'online';
// } else if (status === Status.DELETED) {
// return 'deleted';
/ /}
// return 'error';
// }
Copy the code

4.6 generics

Generic: A type that is generic

// Generics refer to types that are generic

function join<T.P> (first: T, second: P) {
    return `${first}${second}`;
}

function anotherJoin<T> (first: T, second: T) :T {
    return first;
}

// T[]
function map<T> (params: Array<T>) {
    return params;
}

// join<number, string>(1, '1');
// map<string>(['123']);
join(1.'1');
Copy the code

Five, the practice

TypeScript Exercises

TypeScript exercises

Six, extension,

Class definition and inheritance, class decorators, method decorators, accessor decorators, attribute decorators, namespace-namespace, type protection, use of keyof syntax in generics…