Embrace TS (typescript) and face the blast! ! !

 

 

 

Foreword

Since the VUE and TS versions have been built, I have fallen in love with this TS deeply, with a strong type declaration in Java,

It can also serve as a comment. When we see a function, we can immediately know the usage of this function and what value we need to pass.

What type of return value is at a glance has greatly improved the maintainability of large projects.

Woo

Face the blast! ! !

First look at the basics haha

Of course, the official website can also be seen. The following is the link  https://www.tslang.cn/

Basic summary

type of data

  • boolean 、number、string、null、 undefined、 Symbol
  • Undefined and null data can only be assigned undefined and null, but this type is a subtype of all types
  • void empty type
 // undefined and null are all types of subtypes, can be assigned 
    let num: Symbol = undefined; 
    let num: number = undefined;
     // undefined type, only undefined 
    let u: undefined = undefined; 
    let n: null = null

 In fact, the basic types are: + its type to define whether it is more hanging

any and type inference

// In ts, when a variable is declared, if its type is not defined, it will be recognized as the default type 
   let str; 
   str = 'I am strgting' ; 
   str = 1024 ;
    // Undefined type, 
   let num = be assigned directly 124 ; 
    // Equivalent to let num: number = 124, in the following code, if num is given a string, an error will be reported

Multiple possible attributes

 // can only access possible common attributes attribute 
    function getLength (param: String | number) {
         return param.length; 
    } 
    // will complain, because length is not a sting type and number of common attributes 
    // Tips - "use type alias 
    type possibleType = string | number;
     function getLength (param: possibleType) {
         return param.length; 
    }

Interface concept

  • In ts, interface includes an abstraction of behavior, implemented by classes (implements)
  • Also includes a description of the outline of the object

Object interface-"Dynamic Properties

The types of mandatory and optional parameters are a subset of dynamic attribute types, so all types must be set when the dynamic attribute type is set

 interface userinfo {
    "memberId": number,
    "uName": string,
    "employeeId": string,
    "datetime": string,
    "platformList"?: Array<platform>,
    [propName: string]: string | number | Array<platform> | undefined
  }

Binding of read-only attributes

Note: The binding force of the read-only attribute is that the first time the object is assigned a value,

Not the difference between readonly and const when assigning values ​​to attributes: const is a variable, readonly is an attribute

Interface-"Abstract Method Implementation

 export interface ISRequest {
      fetch(url: string, arg?: Object, callback?: Function): Promise<Object>;
    }
    
 export class SafeRequest implements ISRequest {
      public async fetch(url: string, arg, callback?: Function): Promise<Object> {
          return new Promise((resolve, reject) => {      
       })
  }

Representing arrays with interfaces

  interface NumberArray {
        [index: any]: number
    }
  let numArr: NumberArray = [1, 2, 3]

Type of function

  • Optional parameters, must be after required parameters
  • Parameter default
function buildName(firstName: string, lastName?: string) {
        
}

Type assertion

There are two types of writing: angle brackets <> and  as :

let someValue: any = "this is a string";
 
let strLength: number = (<string>someValue).length;
let strLength: number = (someValue as string).length;

 

The usage of type assertion is as above, just add <Type> before the variable that needs to be asserted.
Type assertions are not type conversions. Assertion into a type that does not exist in a union type is not allowed:

function toBoolean(something: string | number): boolean {
    return <boolean>something;
}

 

Enumeration-"two-way mapping of data

Enumeration can be divided into two categories according to the type of enumeration members: numeric enumeration type and string enumeration type;

// enumerate using the enum keyword to declare an enumeration, enumeration and difference digital enumeration of strings 
// is the enumeration member is constant or string; or in the Zodiac as an example: 
// 01- digital gold Enumeration, declares an enumeration whose enumeration members do not have an initializer, 
// The member value of the enumeration starts from 0, and 
enum NumChineseZodiac { 
  rat, 
  cattle, 
  tiger, 
  rabbit, 
  dragon 
} 
// 02-string Enum 
StrChineseZodiac { 
  rat = 'rat' , 
  cattle = 'cattle' , 
  tiger = 'tiger' , 
  rabbit = 'rabbit' , 
  dragon = 'dragon' 
}

Generic: Generics

A major part of software engineering is to build components. The built components not only need to have a clear definition and a unified interface, but also need to be reusable.

Components that support existing data types and data types added in the future provide good flexibility for the development process of large software systems.

In  C# and  Java , you can use "generics" to create reusable components, and components can support multiple data types. This allows users to use components based on their data type

Generic method

In TypeScript,   there are two ways to declare generic methods :

function gen_func1<T>(arg: T): T {
 return arg;
}
// 或者
let gen_func2: <T>(arg: T) => T = function (arg) {
 return arg;
}

There are also two calling methods:

gen_func1 <string> ('Hello world' ); 
gen_func2 ( 'Hello world' ); 
 // The second call can omit the type parameter, because the compiler will automatically identify the corresponding type based on the incoming parameters.

2. Generic and Any

Ts When the specific type  Any of is used, it can replace any type. At first glance, it seems that there is no difference between the two, but in fact it is not:

// Method 1: Method with any parameter 
function any_func (arg: any): any { 
 console.log (arg.length); 
        return arg; 
} 
 
// Method 2: Array generic method 
function array_func <T> (arg : Array <T>): Array <T> { 
     console.log (arg.length); 
        return arg; 
}

Method one, print the  attributes of the  arg parameters  length. Because it  any can replace any type, this method length will throw an exception when the incoming parameter is not an array or an object with  attributes.

Method two, defines the Array generic type of the parameter type  , there must be  length attributes, so no exception will be thrown.

 

3. Generic types

Generic interface:

interface Generics_interface <T> { 
 (arg: T): T; 
} 
  
function func_demo <T> (arg: T): T {
  return arg; 
} 
 
let func1: Generics_interface <number> = func_demo; 
func1 ( 123); // correct Actual parameter of type 
func1 ('123'); // actual parameter of wrong type

 

 

Vue in Typescript

Three great weapons

  • vue-component-class
    • Methods can be directly declared as class member methods.
    • You can declare calculated attributes as class attribute accessors.
    • The default data is treated as a class attribute
    • The hooks of the life cycle of data, render and vue are directly the methods of class members, keep these names, don't conflict
    • For other configuration items, such as props, promises, etc., passed to the decorator function
- vue-property-decorator (component--dependent vue class provides more decorative, code more display)
     - @Emit
     - @Inject
     - @Prop
     - @Provide
     - @Watch
 - vuex- class (and connected vue vuex )
    

Since vue2.5, vue has better support for ts. I prefer this way of writing

import { Component, Vue, Prop } from 'vue-property-decorator'
 
@Component
export default class Test extends Vue {
 @Prop({ type: Object })
 private test: { value: string }

 

Here are a few commonly used @Prop/@Watch/@Component, for more information, see the official documentation for details

import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator'

@Component
export class MyComponent extends Vue {
  
  @Prop()
  propA: number = 1

  @Prop({ default: 'default value' })
  propB: string

  @Prop([String, Boolean])
  propC: string | boolean

  @Prop({ type: null })
  propD: any

  @Watch('child')
  onChildChanged(val: string, oldVal: string) { }
}

The above code is equivalent to:

export default {
  props: {
    checked: Boolean,
    propA: Number,
    propB: {
      type: String,
      default: 'default value'
    },
    propC: [String, Boolean],
    propD: { type: null }
  }
  methods: {
    onChildChanged(val, oldVal) { }
  },
  watch: {
    'child': {
      handler: 'onChildChanged',
      immediate: false,
      deep: false
    }
  }
}

 

These are some simple foundations, still need a lot of practice, I will also give an example of the commonly used ones,

I am going to upload the demo I wrote to GitHub,

Come on, Sao Nian Haha

 

Guess you like

Origin www.cnblogs.com/yf-html/p/12718798.html