preface

Personal learning process: Po of 1.2 W word | great TypeScript introductory tutorial, cooperate with some video edible, finally, the knowledge system to comb again Introductory lesson for net typescript video, Js +TS project of STATION B (very friendly to beginners, write a project in 1 hour ha ha ha, the content involved in the project is relatively comprehensive)

Grammar article



First, basic types

The data type Keyword/Description usage
Numeric types number let decLiteral: number = 6
Boolean type boolean let flag: boolean = true;
String type string let name: string = “Runoob”
An array type array // Add [] to the element type

let arr: number[] = [1, 2];

// Use array generics

let arr: Array = [1, 2];
tuples Fixed the number and type of elements. The types may vary, but the positions must be the same let x: [string, number];

x = [‘Runoob’, 1]; // It is running properly

x = [1, ‘Runoob’]; / / an error

console.log(x[0]); / / output Runoob
The enumeration Enum/Defines a set of values enum Color {Red, Green, Blue};

let c: Color = Color.Blue;

console.log(c); 2 / / output
void Void/means that the method returns no value function hello(): void {

// There is no return value

}
null Null/Object value missing let n: null = null;
undefined Undefined/undefined value let u: undefined = undefined;
never Never /never is a subtype of other types, including null and undefined, and represents values that never occur Ffunction error(message: string): never {throw new error(message); }
unknown Unknown /unknown types can only be assigned to any and unknown types let value: unknown;  

let value1: unknown = value; // OK

let value2: any = value; // OK

let value3: boolean = value; // Error

supplement

Enum type

1. Enumeration: The initial value can be automatically increased. Actual scenario: Article categories with fixed ids can be defined by enumeration

enum Category {
  Work,// There is a default initial value of 0 growing in sequence
  Life,
  Study,
}
  let cateGoryId: Category =Category.Study
  console.log(cateGoryId)/ / 2

Copy the code

** 2. String enumeration ** defined members must be strings. For example, each person will take their Own English name, corresponding English name and real name, you can do one-to-one mapping

enum Person {
  jack = 'wang',
  role = 'little blue',
  Anna = 'little red',}let person: Person =Person.Anna
  console.log(person)/ / the little red
Copy the code

**3. Heterogeneous enumeration ** different: that is, there are both numbers and strings in the member, large miscellaneous stew

enum mess {
  jack = 'wang',
  role = 'little blue',
  Anna = 'little red',
     c = 1,
     b = 2
}
Copy the code

Second, the assertion

Type assertions must be associated with one of the types. Type assertions are only type choices, not type conversions. Compile phase comes into play

const unionGetLength2 = (something: string | number) :number= > {
    if(something.length){ // It is not possible to determine the type of the error
        return something.length;
    } else {
        returnsomething.toString().length; }}Copy the code

You can use assertions to handle problems that cannot be determined by the above type. There are two ways to write an assertion:

  1. As grammar
  2. Angle bracket syntax

1. As syntax (value as type)

const assertionGetLength = (something: string | number) :number= > {
    if((something as string).length){// tell TS something is a string
        return (something as string).length;
    } else {
        returnsomething.toString().length; }}Copy the code

2. Angle bracket syntax (< type > value)

const assertionGetLengthOther = (something: string | number) :number= > {
    if((<string>something).length){tell ts something is a stringreturn (<string>something).length;
    } else {
        returnsomething.toString().length; }}Copy the code

Type guard

1. Type guard

1.1 What is Type Guard

When a conditional statement is encountered, the variable type is limited ****

  • Type judgment:typeof
  • Example judgment:instanceof
  • Attribute judgment:in
  • Literal equality judgment:= =.= = =.! =.! = =

1.2 Type Judgment (Typeof)

function test(own: string | boolean | number) {
  if (typeof own == 'string') {
    // The type of own is limited to string
  } else if (typeof own == 'number') {
    // The type of own is limited to number
  } else {
      // The type of own is limited to Boolean}}Copy the code

1.3 Attribute Judgment (in)

interface one {
  name: string;
  speak:string;
}

interface two {
  age: number;
  see:string;
}


function test(own:one | two){
  console.log("Name: " + own.name);
  if ("name" in own) { 
    // The object is one
    console.log(own.speak);
  }
  if ("see" in own) {
    // the limit is own and the limit is two
    console.log(own.see); }}Copy the code

1.4 Instance Judgment (Instanceof)

interface  Padder {
  getPaddingString():string
}
class Space implements Padder {
  constructor(private numSpaces: number) {} 
  getPaddingString() {
    return Array(this.numSpaces + 1).join(' '); }}class StringPadder implements Padder {
  constructor(private value: string) {}
  getPaddingString() {
    return this.value; }}function getrandom() {
  return Math.random() < 0.5 ? new Space(4) : new StringPadder(' ');
}

let padder: Padder = getrandom();

// Determine if padder is an instance of Space
if (padder instanceof Space) {
  // After checking, make sure the value is its instance object padder type shrinks to 'SpaceRepeatingPadder'
}
Copy the code

2. Custom type guards

Returns a Boolean conditional function

function isString (own: any) :own is string {
  return typeof own === 'string';
}
function test (xdom:any) {
 if (isString(xdom)) {
    	//xdom is limited to 'string'
    } else {
     // Other types}}Copy the code

Join types and type aliases

1. Union type

The value can be one of the following: 1. The attributes and methods used must share 2. Usually used with null or undefined:

let stringAndNumber: string | number;
Copy the code

2. Type alias

Type another nickname, defined by type

Do not use type aliases:let greet = (message: string | string[]) = > {
  // ...}; Alias with type:type Message = string | string[];
let greet = (message: Message) = > {
  // ...
};
Copy the code

Fifth, cross type

Satisfy multiple types at the same time, the multiple types are superimposed into one type, to contain all the required characteristics of the type

interface IPerson {
  id: string;
  age: number;
}

interface IWorker {
  companyId: string;
}

type IStaff = IPerson & IWorker;// Define an IStaff type that satisfies both interface type conditions

const staff: IStaff = { //staff I IStaff type must be satisfied together
  id: 'E1006'.age: 33.companyId: 'EFT'
};

console.dir(staff)
Copy the code

Six, functions,

TypeScript JavaScript
Contains the type No type
Arrow function Arrow function (ES2015)
Function types No function type
Mandatory and optional parameters All parameters are optional
The default parameters The default parameters
The remaining parameters The remaining parameters
Function overloading Function overloading

1. Ordinary functions

You can define the parameter types and return values of a function

function createUserId(name:string,id:number) {
	return name + id
}
Copy the code

2. Arrow function

let createUserId:(name:string,id:number) = >string
Copy the code

3. Optional parameters

? Note: Optional parameters must be placed after normal parameters, otherwise a compilation error will occur

function createUserId(name:string,id:number,age? :number) {
	return name + id;
}
Copy the code

4. Default parameters

The default value of the name parameter is Jons

function createUserId(name:string = 'Jons',id:number) {
 return name + id;
}
Copy the code

5. Remaining parameters

Short for, you can write the rest of the parameters together

function push(array,... items) {
  console.log(items)
}
push(a,1.2.3) //items is an array [1,2,3]
Copy the code

6. Function overload

Common functions that execute different types of arguments are mostly used to pass in different arguments to get different results. Overloading has two parts: 1. Statement 2. Implementation is indispensable

6.1 Reloading Scenarios

Example 1: For example, we have an add function that accepts string for concatenation or number for addition

/ / declare:
function add (arg1: string, arg2: string) :string
function add (arg1: number, arg2: number) :number/ / implementation,function add (arg1: string | number, arg2: string | number) {// In the implementation, we should be careful to determine whether the two parameters are of the same type, rather than simply write onearg1 + arg2
  if (typeof arg1 === 'string' && typeof arg2 === 'string') {
    return arg1 + arg2
  } else if (typeof arg1 === 'number' && typeof arg2 === 'number') {
    return arg1 + arg2
  }
}
Copy the code

Note: If the implementation part is not strictly judged, the overloaded signature is prompted to be incompatible with its implementation signature. Function overloading is just a number of function declarations, and the logic is still written by ourselves. It does not merge the functions we declare. Example 2: Test is passed as a param, but flag is not passed as a param, number is passed as a flag.

interface User {
  name: string;
  age: number;
}

declare function test(param: User | number, flag? : boolean) :number;
const user={
name:'Jack'.age:18
}
const res=test(user,false) // Flag should not be passed when User is passed
Copy the code

Reload to resolve appeals:

interface User{
	name:string;
	age:number;
}
declare function  test(params:User) :number;
declare function  test(params:number,flag:boolean) :number;
const user={
  name:'jack'.age:Awesome!
};
// Type "{name: string; age: number; } "arguments cannot be assigned to arguments of type" number ". ts(2345)
const res=test(user,false);
Copy the code

Usage in real projects: After a declaration, there needs to be a concrete implementation

interface User{
  name:string;
  age: number;
}
const user:User ={
  name:'jack'.age:  123
}
class oneClass {
  / / declare
  public test(param: User): number;
  public test(param: number.flag: boolean) :number;
  / / implementation
  public test(param: User | number, flag? :boolean) {
    if (typeof param==='number') {
      return param+(flag?1:0)}else{
      return param.age
    }
  }
}
Copy the code

If the parameters passed in are different, but the result is the same, then there is little point in overloading. Overloading is tedious. Some overloading can be replaced by other methods, which are much simpler, such as using optional parameters

function func (a: number) :number
function func (a: number, b: number) :number// Replace the above:function func (a: number, b? :number) :number
Copy the code

Use union types instead:

function func (a: number) :number
function func (a: string) :number// replace the abovefunction func (a: number | string) :number
Copy the code

Seven, arrays,

Ts is a type check in this process. If the type is defined, it conflicts with the corresponding data in the following array

// Cannot assign type "number" to type "string"
let x: number;
let y: number;
let z: string;
let five_array = [0.1.2.3.4];
[x, y, z] = five_array;
Copy the code

1. Primitive arrays

Define an array containing only numbers:

const arr: number[] = [1.2.3]
Copy the code

Store both numbers and strings:

const arr1: (number | string) [] = [1.'2' ,3]
Copy the code

2. Array of object types

const objectArr: {name: string.age: number} [] = [{name:'a'.age:16}]
Copy the code

3. Compare with tuples

Tuples are essentially arrays, so operation tuples on arrays can also be used when the length and type of an array are fixed

const teacherinfo2: [string.string.number] = ['zina'.'girl'.18];
// Here is the fixed length and fixed each type, if the type is different will be prompted
Copy the code

Eight, interfaces,

Interface to define the type of an object

1. Write

2. The shape of a variable must be the same as the shape of the interface.

interface Person {
  name:string
  age:number
}
let jack:Person = { // The type of the variable must be the same as above
	name:'jack'.age:18
}
Copy the code

2. Optional properties

As with arrays, properties in objects are optional, and we often need objects of different shapes

interface Person {
  name:stringage? :number
}
  let jack:Person = { 
	name:'jack' // age can be omitted
}
Copy the code

3. Arbitrary attributes

Scenarios for determining the number of attributes and optional attributes must both conform to the type of any attribute if not the following:

interface Person {
  name: string; age? :number;
  [propName: string] :string;
}
// Attribute "age" of type "number" cannot be assigned to string index type "string".
Copy the code

Correct way to write:

interface Person {
name:string; age? :number;
[proppName:string] :any;
}
Copy the code

4. Read-only attribute

Some fields can only be assigned at creation time, and others cannot be changed. Read-only properties can be used

interface Person {
    readonly id: number;
    name: string; age? :number;
    [propName: string] :any;
}

let tom: Person = {
    name: 'Tom'.gender: 'male'
};

tom.id = 89757;
// "id" cannot be assigned because it is read-only
Copy the code

Nine, generics

A situation where the type is not clear, but some or all of the types are required to be consistent

Usage scenarios

If you want the type of the variable to be first, second must be the same

function test(first:any.second:any){
  return `${first}+${second}`
}
Copy the code

Generic solution: T is custom, ABC can be used

function test<T> (first: <T>,second: <T>){
  return `${first}+${second}`
}
test<number> (1.1)
test<number> (1.'1')/ / an error
Copy the code

You can define a type in an array

function map<T> (params:T[]){
  returnAnother way to write params}function map<T> (params:Array<T>){
  return params
}

map<string> ([1.'1'])/ / an error
map<string> (['1'.'1'])
Copy the code

Define multiple generics:

function test<T.P> (first:T,second:P) :T{
 return first  // Return the same type as first
}
test<string.number> ('1'.1)
test('1'.1) // If you do not define a type, ts automatically concludes that T is a string and P is a number
Copy the code

Ten, class,

1. How to define a class

class Person {
  name = 'dell'
  getName(){
    return this.name; }}const person = new Person();
console.log(person.getName())//dell 
Copy the code

2. Class inheritance

class Person {
  name = 'dell'
  getName(){
    return this.name; }}class Teacher extends Person {
  getTeacherName(){
    return 'teacher'}}const teacher = new Teacher(); GetTeacherName getTeacherName getTeacherName getTeacherName
console.log(teacher.getName()); //dell
console.log(teacher.getTeacherName()) //teacher
Copy the code

3. Class overrides and super

Superclass methods can be subclassed to override the superclass method. **super is used to override the superclass method

class Person {
  name = 'dell'
  getName(){
    return this.name; }}class Teacher extends Person {
  getTeacherName() {
    return 'teacher';
  }
  getName() {
    return 'lee'; }}console.log(teacher.getName());// the subclass getName overwrites the parent class getName
// if Teacher writes as follows
class Teacher extends Person {
  getTeacherName() {
    return 'teacher';
  }
  getName() {
   // super.getName()// calls the method of the parent class
    return 'lee' + super.getName(); }}Copy the code

4. Access type

4.1 Private

To allow use within a class first of all what is in a class and what is out of a class

class Person {
 private name = 'dell'
  getName(){
   console.log(this.name)// The class can be called}}const person = new Person()
console.log(person.name) // This is an out-of-class error
Copy the code

4.2 Protected

Allows use within classes and in inherited subclasses

class Person {
 protected name = 'dell'
  getName(){
   console.log(this.name)// The class can be called}}class Teacher extends Person {
  getTeacherName() {
   console.log(this.name)// Name inherited from the parent class is allowed to be called}}Copy the code

4.3 public Public

It allows me to be called inside or outside of the class, and if I don’t write it’s public by default

class Person {
  name = 'dell'// Public name by default
  getName(){ Public getName by default
   console.log(this.name)
  }
}
const person = new Person()
console.log(person.name)
Copy the code

5. The constructor function

The moment constructor() is executed immediately when the new instance is created

Traditional writing:class Person {
  public name:string
  constructor(name:string){
    this.name=name
 }
}
const person =new  Person('dell')
console.log(person.name) can be simplified as:class Person {
  constructor(public name: string){}}Copy the code

If the parent class has a constructor and the child class has a constructor, the child class must call the parent class’s constructor. The arguments must also be passed in as required by the parent class’s constructor

class Person{
constructor(public name:string){}}class Teacher extends Person{
  constructor(public age:number){
    super('dell')}}const teacher =new Teacher(28)
console.log(teacher.age)/ / 28
console.log(teacher.name)//dell
Copy the code

6. Getter and setter

For example, if a class has a private variable and needs to expose it to the outside world, it can use the following method: Getters and setters can process variables and expose them to the outside world, which calls get/set to read the change _name property

class Person{
  constructor(private _name:string){
  get name() {return this._name+' lee'; // The name can be encrypted and exposed
  }
  set name(name:string) {// Can also protect variables
    const realName=name.split(' ') [0]; // Perform a processing on the resulting name
    this._name=realName
  }
}
const person=new Person('dell')
console.log(person.name);// Dell Lee does not need parentheses
person.name ='dell lee'
Copy the code

7. Examples (singleton pattern)

Only one instance is ever created, and when it is found that an instance has already been created, no more instances are created

class Demo{
  private static instance:Demo 
  private constructor(public name:string){}// It is not allowed to be called to circumvent instance creation
  static getInstance(){
    if(!this.instance){ // If no instance is created let instance store
    this.instance = new Demo('dell lee')}return this.instance; }}const demo1 =Demo.getInstance();
Copy the code

8. An abstract class

Extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends extends Calculate rectangular, circular ellipse area directly write so each of the class is a class need to write this method, this method can be extracted by writing in an abstract class, rectangle, circle, elliptic to inherit the abstract class, the shape of the area of calculation formula is different, the specific implementation in her class to write specific writing:

abstract class Geom{ //abstract defines an abstract class
  getType(){
    return 'gemo';
  }
  abstract getArea():number // The abstract method has no concrete implementation
}
class Circle extends Geom{
  private r:number
getArea(){
  return '123'}}class Square extends Geom{
getArea(){
  return 'hello'}}class Triangle extends Geom{
getArea(){
  return ' '}}Copy the code

11. Decoration

1. What are decorators

The decorated tool decorator is itself a function

2. Types of decorators

  • Class decorator
  • Method decorator
  • Accessor decorator
  • Property decorator
  • Parameter decorator

Class decorator

3.1 How to write a decorator

through@You can’t use decorators directly. For experimental syntax in the standard, you need to open the configuration item in the tsconfig.json file



function testDecorator(constructor:any){
  constructor.prototype.getName = () = > {console.log('dell')}console.log('decorator')}@testDecorator
class Test{}// The runtime is executed immediately after the class is created


const test = new Test();
Copy the code

3.2 Execution order of multiple decorators

You collect it from top to bottom but you execute it from bottom to top

function testDecorator1(constructor:any){
  console.log('decorator1')}function testDecorator2(constructor:any){
  console.log('decorator2')}@testDecorator1
@testDecorator2
class Test{}
// console:
//decorator2
//decorator1
Copy the code

3.3 Decorator packaging

Sometimes there is some judgment in the decorator, you can wrap the decorator in factory mode and return a function inside

function testDecorator(flag:boolean){ // Receives the decorator's parameters
  if (flag) {
    return function (constructor: any) {
      constructor.prototype.getName = () = > {console.log('dell');
      };
      console.log('decorator');
    };
  }else{
    return function (constructor: any) {}}}@testDecorator(false)// The decorator returns a function, which is then called
class Test{}
Copy the code

Method decorator

The method decorator takes three arguments

  • Targe: normal method, target object is the class prototype, if the static method target corresponds to the class constructor
  • Key: The name of the method that decorates the normal method key
  • **descriptor: ** attribute descriptor
function getNameDecorator(target:any,key:string,descriptor:PropertyDecorator){
  console.log(target, key, descriptor);
};
Copy the code

How do I keep a method from being modified after the instance is created? How do I change the original value of a method? You can control it with descriptor

function getNameDecorator(target:any,key:string,descriptor:PropertyDescriptor){
  console.log(target, key, descriptor);
  descriptor.writable=false // Methods are not allowed to be modified
  descriptor.value = function() { // Change the original value returned from the method
    return 'yeyeyeye'}};class Test{
  name:string;
  constructor(name:string){
    this.name=name;
  }
  @getNameDecorator
  getName(){ // As soon as the class is created, decorate the method
    return this.name
  }
}
const test =new Test ('dell')
test.getName=() = >{ //error
  return '123'
}

Copy the code

Accessor decorators

Accessor decorators receive the same arguments as method decorators. Accessor decorators receive three arguments

  • Targe: normal method,target object is the class prototype, if the static method target corresponds to the class constructor
  • Key: The name of the method that decorates the normal method key
  • **descriptor: ** attribute descriptor

Write a decorator for set:

function visitDecorator(
  target: any,
  key: string,
  descriptor: PropertyDescriptor
) {
  console.log(target, key, descriptor);
  descriptor.writable = false; // Methods are not allowed to be modified
};
class Test{
private  _name:string;
  constructor(name:string){
    this._name=name;
  }
  get name() {
    return this._name;
  }
  @visitDecorator
  set name(name:string) {this._name = name; }}const test =new Test ('dell')
test.name = '123123' Writable = false does not allow modification of the set descriptor
console.log(test.name) // use the get method
Copy the code

6. Property decorators

The property decorator takes two arguments

  • Targe: normal method, target object is the class prototype, if the static method target corresponds to the class constructor
  • Key: the name of the property to be decorated

You can define your own descriptor and return a new descriptor to override the original descriptor, like the following: You can change the name, you can’t change the writable to false in descriptor

function nameDecorator(
  target: any,
  key: string.) :any{
  console.log(target, key);
  const descriptor :PropertyDescriptor ={
    writable:false
  }
  return descriptor;
};
class Test{
 name:string='dell';
}
const test =new Test ()
test.name = '123123'
Copy the code

7. Parameter decorator

The parameter decorator accepts three parameters

  • Prototype targe:
  • Method: indicates the name of the method
  • ParamIndex: indicates the position of the parameter
function paramDecorator(target: any, method: string,paramIndex:number) :any {
  console.log(target, method, paramIndex); // Prototype getInfo 0
};
class Test{
 getinfo(@paramDecorator name:string,age:number){
   console.log(name,age)
 }
}
const test =new Test ()
test.getinfo('dell'.30)
Copy the code

Vue.js+TS project practice

1. Project environment construction

npm i -g @vue/cli // Install vUE scaffolding
vue create vueAddts // Create vUE project
vue add @vue/typescript / / create @ vue/typescript
npm i vuex  / / vuex installation
Copy the code

2. Differences between Vuejs version and Vuejs+TS version

**TS :** You need to import two components, the Vue Component annotation, which registers the Component vue-property-decorator property as follows:

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import ResList from '@/components/ResList.vue'

@Component({
  components: {
    ResList
  }
})
export default class extends Vue {}
Copy the code

Vue version: Object way to describe the entire Vue

<script>
export default {
  name: "App".data(){
  return{}}}; </script>Copy the code

3. Project address

This project is a tag application written by TS+ vue.js video, which is very friendly to beginners and highly recommended for small partners to see ~

Run the following command to add or delete labels and modify categories



If you’re interested, you can click hereProject linkTo view

4. Great tsconfig.json guide

Tsconfig. json is a great guide to tsconfig.json

On time

It took about 4 days to learn. In the first part of the time, I was not focused. I watched TS and other knowledge points for a while, which wasted a lot of time and was very inefficient

It is too difficult to write such a long article for the first time. I do not know if I have picked up my liver. Please return it to me, crab crab

As a senior water injection master, technical dish of the foot stickers, put before I would never believe that I can write such a long, before the most paste code, add a few lines of words



Is the interview very awkward, put their own blog, put in the corner, too water, afraid of being sprayed ha ha ha. If do not put it, and unwilling, is such a contradiction.

Thank you very much Po elder brother and master’s guidance, turn over a new leaf and strive for the future is not so water ~.

₍₍Ϡ(੭•̀ω•́)੭✧⃛

Refer to the article

How to write a Typescript declaration file 1.2 W word | great Typescript introductory tutorial