What is?

TypeScript is a superset of JavaScript types that extend JavaScript syntax to support ES6 syntax (remember this picture)

The basic grammar

The data type

  • Boolean (Boolean type)
  • Number (number type)
  • String (String type)
  • Array (Array type)
  • Tuple (tuple type: elements do not have to be of the same type)
  • Enum (Enumeration type)
  • Any (any type)
  • Null and undefined
  • Void type
  • Never type
  • Object Object type
//boolean
let flag:boolean = true;
//number
let num:number = 123;
//string
let str:string = 'this is ts';
//array
let arr:string[] = ['12'.'23'];  // Define a string array
let arr:number[] = [10.20];  // Define an array of numbers
let arr:Array<number> = [1.2];  // Array< element type >

//tuple
let tupleArr:[number.string.boolean]; 
tupleArr = [12.'34'.true]; //ok
typleArr = [12.'34'] // no ok

//enum
enum Color {Red, Green, Blue = 100}
let c: Color = Color.Green;  // If no value is given, the return index is 1
let d:color = Color.Blue; // Return 100 if there is a value

//any
let num:any = 123;
num = 'str';
num = true;

/ / null, and undefined
let num2:undefined 
let num3:null
num3 = null

// Viod has no return value
function hello() :void {
    alert("Hello Runoob");
}
//never is used to specify an infinite loop that always throws an exception
let a:never;
a = 123; // This is not the case
a = (() = > { // The correct way to write
  throw new Error('wrong'); }) ()function error(message: string) :never {
    throw new Error(message); // Throw an exception
}

// object
let obj:object;
obj = {name: 'Wang'.age: 25};
Copy the code

function

The function type depends on the return value type

// Declaration mode: When a function is overloaded, only mode 1 can be used
/ / way
type LongHand = {
  (a: number) :number;
};
function func(a: number) :number{
	return a
}
2 / / way
type ShortHand = (a: number) = > number;
Copy the code
// Optional parameters are available
const add = (a: number, b? :number) = > a + (b ? b : 0)
function add(a: number, b? :number) :number{
	if(b){
	  return a+b
	}else{
	  return a
	}  
}
Copy the code
// Remaining parameters
const add = (a: number. rest:number[]) = > 
	rest.reduce(((a,cur) = > a + cur), a)
Copy the code
// For example, we have an add function that accepts arguments of type string for concatenation,
// You can also take arguments of type number and add them
function add (arg1: string, arg2: string) :string
function add (arg1: number, arg2: number) :number// If the type of the two parameters is the same, the type of the two parameters is the samearg1 + arg2
function add (arg1: string | number, arg2: string | number) {
  if (typeof arg1 === 'string' && typeof arg2 === 'string') {
    return arg1 + arg2
  } else if (typeof arg1 === 'number' && typeof arg2 === 'number') {
    return arg1 + arg2
  }
}
Copy the code

class

Definition and Inheritance

class Animal { 
    / / field
    name:string; 
    // constructor
    constructor(n:string) { 
        this.name = n 
    }  
    / / method
    say():void { 
        console.log(`Animal name is The ${this.name}`); 
    } 
    doPrint():void {
      console.log("Parent's doPrint() method.")}}/ / inheritance extends
class Dog extends Animal {
	color:string;
	construtor(n:string){
		super(n);  // Inherits the superclass attributes
		this.color = 'Default color'
	}
    bark() {
        console.log('Woof! Woof! ');
    }
    // Override the parent method
    doPrint():void { 
      super.doPrint() // Call the parent function
      console.log("Subclass's doPrint() method.")}}const dog = new Dog();
console.log(dog.name);
console.log(dog.color)
dog.say();
dog.bark();
Copy the code

The modifier

Public public: Allows free access to members defined in class programs

Readonly: Read-only attributes must be initialized at declaration time or in a constructor and cannot be modified

Static properties: static – These properties are accessed by type. This form of access to static properties

class Square {
    static width = '100px'
}

console.log(Square.width) // 100px
Copy the code

Abstract class: cannot be created, is used to subclass inheritance template, keywordabstract

// The method subclass that defines the abstract keyword must have!
abstract class Animal {
    abstract makeSound(): void;
    move(): void {
        console.log('roaming the earch... '); }}// Inherited by subclasses
class Cat extends Animal {
    makeSound() {
        console.log('miao miao')}}const cat = new Cat()

cat.makeSound() // miao miao
cat.move() // roaming the earch...
Copy the code

Polymorphic: For example, a parent class defines a method, and subclass inheritance can have its own representation

class Animal {
    eat():void{}}// Inherited by subclasses
class Cat extends Animal {
   eat():void{
   	console.log('Cats eat fish')}}class Dog extends Animal {
   eat():void{
   	console.log('The dog eats the bone')}}Copy the code

interface

The purpose of an interface is to define a convention for naming these types and for your code or third-party code, the keyword interface

The attribute interface

interface User {
    name: string
    age: number
}

const getUserName = (user: User) = > user.name  // The age attribute is missing
// Or make age optional
interface User {
    name: stringage? :number
}
Copy the code

The function interface

interface sum{
// The convention of parentheses for arguments, followed by a colon for return constraints
	(num1:number.num2:number) :number
}
var total:sum = function(num1:number,num2:number) :number{
	return num1 + num2
}
console.log(total(30.20))
Copy the code

Arrays, object interfaces

// Array: brackets constrain indexes, followed by constraints on elements
interface arrItf{
	[index:number] :number
}
// Object: Parentheses are constraints on keys, followed by constraints on values
interface objItf{
	[index:string] :any
}
Copy the code

The class interface

// If there is inheritance, the interface is inherited first
interface classItf{
	color:string;
	eat():viod;
}
class Animal{
	name:string;
	constructor(n:string){
		this.name = n 
	}
}
class Dog extends Animal implements classItf{
	color:string;
	construtor(n:string){
		super(n);  // Inherits the superclass attributes
		this.color = 'black'
	}
	eat():void{
		console.log('Bone eating')}}Copy the code

Interface inheritance

interface Father {
    color: String
}
interface Mother {
    height: Number
}
interface Son extends Father,Mother{
    name: string
    age: Number
}
// Define a class that conforms to the above interface conventions
class Childer implements Son{
	color: string;
	height: number;
	name: string;
    age: string; . }Copy the code

The generic

The type is determined by incoming content, expressed in the form of <>

function

function returnItem<T> (para: T) :T {
    return para
}
returnItem<number> (10)
returnItem<string> ('hello')

// Multiple type parameters, tuples
function swap<T.U> (tuple: [T, U]) :U.T] {
    return [tuple[1], tuple[0]];
}

swap([7.'seven']); // ['seven', 7]
Copy the code

class

class Stack<T> {
    arr: T[] = []
    pushFn(item: T) {
        this.arr.push(item)
    }
    getFn():T {
        return ths.arr[1]  // Returns the second value of the array}}let obj = new Stack<number>()
obj.pushFn(20);
obj.pushFn(30);
obj.getFn()
Copy the code

interface

/ / way
interface config{
	<T>(val:T):T
}
let getData:config = function<T> (val:T) :T{
	return val
}

2 / / way
interface config<T>{
	(val:T):T
}
function getData<T> (val:T) :T{
	return val
}

let getStringData:config<string> = getData;
let getNumberData:config<number> = getData;
Copy the code

The module

export {xx,xx,xx}     => import {xx,xx,xx} from '... '
export default {xx1,xx2,xx3}  => import a from '... '
a.xx1
a.xx2
a.xx3
Copy the code

The namespace

Internal modules are also called namespaces: One of the most explicit purposes of namespaces is to solve the namespace problem

// All exposed
export namespace A {
   interface ISomeInterfaceName {      }  
   class SomeClassName {}... }namespace B {
// Local exposure
   export interface InterfaceName {      }  
   export class SomeClassName {}... }Copy the code

A decorator

DefineProperty is a special type of declaration that can be attached to class declarations, methods, accessors, properties, or arguments

Is a way to dynamically extend object functionality without changing the original class or using inheritance

// The method decorator does not change the original code base, adding new functions
// For example, calculate the process of adding 1 to 10000000000
// Original code: add
// The decorator function: count the time
function logMethod(p:any){
	return function(target:any,methodName:any,desc:any){
		console.log(target);  // Constructor/prototype object
		console.log(methodName);  / / the method name
		console.log(desc);  // Method reference
		console.log(p);  / / parameters

	// Override the method
		let oldMrthod = desc.value;
		desc.value = function(){
			// Get the start timestamp
			let start = new Date().getTime()
			// Execute the original code
			let mysum = oldMrthod()
			// Get the end time
			let end = new Date().getTime()
			// Count the time
			let ret = end - start / 1000;
			console.log('The total time is${ret}Second `)
			return mysum  // Return the calculated result}}}class Myclass{
	@logMethod(' ')
	sum():number{
		let sum = 0;
		for(let i= 0; i<10000000000; i++){ sum+=1
		}
		return sum
	}


}

Copy the code

use

Refer to the two articles vue React for details