This is the sixth day of my participation in Gwen Challenge

Installing parsing Tools

  • npm install typescript -g

  • Run TSC filenames.md to compile the ts file into a js file with the same name

The data type

Basic data types (primitive types), complex data types (object types)

number

  • let age: number=18

string

  • let name: string ='Tom'

boolean

  • let isPass: boolean =true

undefined

  • let un: undefined=undefined

null

  • let nu: null =null

array

  • Let arr: string [] = [‘ a ‘, ‘b’, ‘c’] let arr: number [] = [18,19,20]

    Generic let arr: Array < string > = [‘ a ‘, ‘b’, ‘c’] let arr: Array < number > [] = [18,19,20]

function

function sayHi():string{
	return 'hi'
}
let a=sayHi()
Copy the code
function sayHi():void{
	console.log('hi')
}
Copy the code

The tuple:

  • Tuples –> specify the number of elements in an array and the data type of each element. The types can be different

Create the let tup1: [number, string, Boolean] = [1, ‘Tom’, true]

Reassign tup1=[2,’jack’,false]

Get element tup1[0],tup1.length

enum

create

enum Gender{
    boy,
    girl,
    unknow
}
Copy the code

Use the console. The log (Gender. The boy)

Let sex:Gender = Gender. Boy

any

  • Any type, typically used to get DOM objectslet txtName: any=document.getElementById('txt')

never

  • The type of a nonexistent value, often used to throw an exception, or an infinite loop of functions

    function test() :never{
    	while(true) {}}Copy the code
    function test() :never{
    	throw new Error('wrong! ')}Copy the code

void

  • No type, used for functions that have no return value

Type inference

If the declaration of a variable is initialized on the same line, you can omit the declaration of the variable type.

Once the type is deduced, changing the type of the variable elsewhere will result in an error

let x = 3 //x is inferred to be type number
Copy the code

let arr=[1.'aaa'.null] //x will infer the number string null type
Copy the code

In some cases, the expected type cannot be inferred, and you need to specify the type

let zoo: Animal[] = [new Rhino(), new Elephant(), new Snake()];
Copy the code

If there is no find the best general type, type inference as an associative array type, the result of the (Rhino | Elephant | Snake) [].

The joint type

The value of a variable can be one of many types

Let the variable name, variable type 1 | variable type 2 = value — — — — — — — — — — — — — – > let name: string | null = prompt (‘ input name ‘) name can be a string or null type

function

Returns the value and type

Functions must have a return value type

The parameter must be of the same type

The number of arguments must be the same

function sayHi(words: string) :void{
	console.log(words)
}
sayHi('hello')//hello

Copy the code

Optional parameters

Optional arguments can be passed or not

function sayHi(words? :string) :void{
	console.log(words)
}
sayHi()//undefined
Copy the code

Default value (optional)

The same as the default argument for the ES6 function

function sayHi(words='hello') :void{
	console.log(words)
}
sayHi()
sayHi('world')
Copy the code

Sometimes you only need to pass the second parameter, in which case you just need to set the first parameter to undefined

The remaining parameters

An uncertain number of parameters, such as the number of parameters in an addition operation

function add(parameter1Type:1The parameter2Type:2. parameter3Type: []) :void{}Copy the code

Only one remaining parameter can be defined

The remaining parameters can only be defined as an array

The remaining parameters can only be written at the end of the parameter list

function add (x:number,y:number. restOfNum:number[]) :void{
	 let resNum: number =x+y;
	 for(let item of restOfNum){
	 	resNum+=item
	 }
	 console.log(resNum)
}
add(1.2) / / 3
add(1.2.3.4.5) / / 15
Copy the code

Function overloading

To allow the same function to do different things when passing in different arguments

  • Use union types for overloading
function getNum(num: number | string) :number {
  if (typeof num == "string") {
    return Number(num);
  }
  if (typeof num == "number") {
    returnnum; }}let num = getNum("23");
console.log(num);
console.log(typeof num);
Copy the code
  • Declare the function repeatedly and implement it one last time
function getInfo(name: string) :void;
function getInfo(age: number) :void;
function getInfo(str: any) :void {
  if (typeof str == "string") {
    console.log("Name:", str);
  }
  if (typeof str == "number") {
    console.log("Age", str);
  }
}
getInfo("zs");
Copy the code

As you can see, the main implementation idea is to perform different operations in a specific function by determining the type of argument passed in by if/switch

Compile result:

interface

  • Describe a thing and place some constraints on it, such as: required, optional, read-only, etc
function printLabel(labelledObj: { label: string }) {
  console.log(labelledObj.label);
}

let myObj = { size: 10.label: "Size 10 Object" };
printLabel(myObj);
Copy the code

If the type is different from the specified one, the editor prompts an error

When attributes are used in a function, they need to be declared one by one

function printLabel(labelledObj: {
  label: string;  //The statement label size:number; //Declare the size isCheck:boolean; //The statement isCheck}) {
  console.log(labelledObj.label);  / / use the label
  console.log(labelledObj.size);  / / use the size
  console.log(labelledObj.isCheck); / / use isCheck
}

let myObj = { size: 10.label: "12".isCheck: true };
printLabel(myObj);

Copy the code

This approach works, but the code is verbose, so you can use interfaces as specifications

The attribute interface

  • Basic operation, this parameter must be set
interface Name {
	label: string;
}
function setName(nameObj: Name) {
	console.log(nameObj.label);
}
// When called, the argument type must be the same as the interface, the property type must be the same, and the property must be included
setName({
	label:'xiaohong'
})/ / output xiaohong
Copy the code
  • You can pass in additional parameters
interface Name {
	label: string;
}
function setName(nameObj: Name) {
	console.log(nameObj.label);
}
// Define a separate object externally. It can have additional attributes, but the attributes defined in the interface must be wrapped
let obj={
	label :'xiaohong'.age:18,
}
setName(obj)
Copy the code
  • ? Set Optional Properties Properties Are optional
// When defining an interface, place a question mark after an indeterminate attribute.
interface Name {
	label: string;
	isEnglishName? :boolean
}
Copy the code

The function interface

  • Describes the parameter types and return values of a function

  • Basic operation

interface eat{
   (name:string.food:string) :void
}
let breakfast:eat =function(name:string,food:string){
   console.log(name,food)
}
breakfast('breakfast'.'the steamed stuffed bun')// Breakfast buns
Copy the code
  • Optional parameters
interface eat{
	(name:string,food? :string,) :void// Add?
}
let breakfast:eat =function(name:string,food='didn't eat){// Give a default value, otherwise output undefined
	console.log(name,food)
}
breakfast('breakfast')
Copy the code
  • Uncertain parameters
interface eat{
	(name:string. food:string[]) :void
}
let breakfast:eat =function(name:string. food:string[]){
	console.log(name,food.join())
}
breakfast('breakfast'.'the steamed stuffed bun'.'soya-bean milk.'Fried dough sticks')// Breakfast steamed stuffed bun, soybean milk, fried dough sticks
Copy the code

Class interface — — — — — implements

  • Can implements multiple interfaces

  • Explicitly forcing a class to conform to a contract

  • Interfaces describe the common parts of a class in which additional attribute methods can be defined

interface Animal {
	name: string; //
	eat(): void;
}
class Dog implements Animal {
	name: string;  // Declare attributes
	constructor(name: string) { // The argument passed when the object is created
		this.name = name;  / / assignment
	}
	eat() { // The function is written directly inside the class
		console.log(this.name); }}let dog = new Dog('xiaohei');
dog.eat()
Copy the code

Interface Inheritance interface

interface Alarm {
    alert(): void;
}

interface LightableAlarm extends Alarm {
    lightOn(): void;
    lightOff(): void;
}
Copy the code

Interface inheritance class

Classes and objects

Create an object

  • Native js
function City(cName, cLevel) {
	this.cName = cName;
	this.cLevel = cLevel;
}
City.prototype.about = function() {
	console.log(this.cName, this.cLevel);
};
const city = new City('shanghai'.1);
city.about();//shanghai , 1
Copy the code
  • ts
class City {
    // Declare attributes
	cName: string;
	cLevel: number;
	
	constructor(cName: string, cLevel: number) {   // Initializes the declared properties
		this.cName = cName;
		this.cLevel = cLevel;
	}
	about() {  // Mount method
		console.log(this.cName, this.cLevel); }}const city = new City('shanghai'.1);
city.about();//shanghai , 1
Copy the code

inheritance

Only one class can be inherited.

Another point about inheritance is that if you now have a class that implements the Square interface, you need to implement not only Square’s methods, but also the methods in the interface that Square inherits, using the implements keyword.

  • The parent class
class City {
	cName: string;
	cLevel: number;
	
	constructor(cName: string, cLevel: number) {
		this.cName = cName;
		this.cLevel = cLevel;
	}
	about() {
		console.log(this.cName, this.cLevel); }}Copy the code
  • A subclass
class Area extends City{
	constructor(cName, cLevel) {
		super(cName,cLevel);If constructor is written, super must be called}}const area =new Area('shanghai'.1);
area.about() //shanghai 1
Copy the code

About super

  • Super is used to call methods of the parent class

Polymorphism (similar to rewriting)

A parent class defines a method that is not implemented and lets its inherited subclasses implement it, each of which behaves differently

// Define the parent class
class Animal_Plant{
	eat(f){
		console.log('cannt eat')}}// rewrite the eat method
class Dog extends Animal_Plant{
	eat(f){
		console.log('can eat' ,f)
	}
}

class Flower extends Animal_Plant{}let dog =new Dog()
dog.eat('meat') //can eat meat
let flower =new Flower()
flower.eat('something') //cannt eat
Copy the code
  • The parent class defines methods, and the subclass inherits methods to achieve different effects
  • Subclasses that do not implement this method can use the default in their parent class

The modifier

  • Public: public type —–> Classes, subclasses, and external classes are accessible. Attributes and methods are accessed by defaultpublic
  • Protected: protection type —–> class, accessible in subclasses but not outside classes
  • Private: private type ———-> Can only be accessed within the class, the rest are not accessible
class Animal {
  public name;
  public constructor(name) {
    this.name = name; }}let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
console.log(a.name); // Tom
Copy the code

Abstract classes – the abstract

abstract class Animal {
  public name;
  public constructor(name) {
    this.name = name;
  }
  public abstract sayHi();
}

class Cat extends Animal {
  public sayHi() {
    console.log(`Meow, My name is The ${this.name}`); }}let cat = new Cat('Tom');
Copy the code
  • Abstract classes cannot be instantiated and can only be inherited by subclasses
  • If an abstract method exists in a class, it must also be implemented in a subclass

Personally, I understand that an abstract class is a skeleton, a template, that must be filled in by subclasses to implement the details

Static properties and methods -static

class Person {
  A: string = "A";
  static B: string = "B";  // Static attributes
  static fun() {  // Static method
      console.log(this.A) //undefined cannot be retrieved
    console.log(this.B);  //B Static methods can only call static properties within the class
  }
    fun1() {
        console.log("Non-static method".this.A); //A Non-static methods can only call non-static properties
        console.log("Non-static method".this.B);// undefined cannot get static attributes}}console.log(Person.B);//
Person.fun();// Static methods and properties can be called without instantiation
console.log(new Person().A); // Non-static requires instantiation



Copy the code

The generic

  • The type of the return value is the same as the type of the parameter passed in,

The function of generic

function getData<T> (value:T) :T{
	return value
}
function getData<T> (value:T) :void{
	// return value
	console.log(value)
}
Copy the code

A generic class

 
Copy the code

Interface generics

The first way to write it

interface Config {
	<T>(value:T):T;
}
let getDate:Config =function<T> (value:T) :T{
	return value
}
console.log(getDate<number> (1212))
Copy the code

The second way to write it

interface Config<T> {
	(value:T):T;
}
function getData<T> (value:T) :T{
	return value
}
let myGetData:Config<string> = getData
console.log(myGetData('xiaohong'))
Copy the code

The namespace

Solve the problem of name duplication

  • Encapsulating namespace
namespace A{
	// If the namespace is private by default, use export to expose it for external use
	export class Dog{... }... }namespace B{
	export class Dog{... }export. }Copy the code
  • use
let adog=new A.Dog()
adog.eat()
let bdog =new B.Dog()
bdog.eat()
Copy the code

Encapsulation uses namespaces

You can pull out the namespace, put it in a TS file, and then expose it externally via export

/ / the new module. Ts
export namespace A{
	export class Dog{...}
	...
}
export namespace B {
	export class Dog{... }export class Cat{...}
    ...
}
Copy the code
// External use
import {A,B} from 'module.ts'
 
let adog=new A.Dog()
adog.eat()
let bdog =new B.Dog()
bdog.eat()

Copy the code

A decorator

A decorator is a method that can be injected into classes, methods, properties, and parameters to extend the functionality of class methods, properties, and parameters

Common decorator (cannot pass parameters)

function logClass(params:any){
	console.log(param)/ / the current class
	params.prototype.url='XXX'// Add an attribute
	params.prototype.get=function(){// Add a method}}@logClass
class HttpClient{
	construtor(){}getData(){}}Copy the code

Factory decorator (recommended for transferable reference)

function logClass(params:string){
		return function (target:any){
				console.log(target) / / the current class
				console.log(params) // hello world}}@logClass('hello world')
class MyHttp{
	constructor(){}getData(){}}let http:any =new MyHttp()
Copy the code