当前位置:网站首页>Basic explanation of typescript

Basic explanation of typescript

2022-07-05 06:11:00 Crisp bamboo book pavilion under the moon

Type notes


/** *  Type notes : Add type constraints to variables  * let  Variable name : type  =  Initial value  */
let age:number = 18;
age = 123;

TS type


/** * ts type : *  The original type :number/string/boolean/null/undefined/symbol *  object type :object( Array 、 object 、 function ) *  newly added ts type : *  Joint type  *  Custom type  *  Interface  *  Tuples  *  Literal type  *  enumeration  * void * any */

let num:number = 18; // value type 
let myName:string = " Zhang San ";// String type 
let isLoading:boolean = true;// Boolean type 
let un:undefined = undefined;//undefined
let timer:null = null;//null
let sym:symbol = Symbol();

TS Type inference mechanism

/** * TS  The type inference mechanism will automatically provide the type  *  as follows  a The default is number type  * add  The default is number type  */

let a = 1;

function add(a:number,b:number){
    
   return a+b;
}

Joint type

/** *  Joint type : When a value can be either number type   It may also be for null when , You need a new type  * ( The variable can be null perhaps number type ) */
let unite:number|null = null;
    unite = 2;

Type the alias

/** *  Type the alias : When the defined type name is very long , You can define aliases , Easy to write ( title case !!--NewType) *  effect : * 1. Alias the definition  * 2. Defines a new type  */
type StringNumber = string | number;
let myColor:StringNumber = "red";
myColor = 124;

An array type

/** *  An array type  *  How to write it 1:let num: type []= [ value 1,...] *  How to write it 2:let num:Array< type > = [ value 1,...]; * */
// How to write it 1
let numbers:number[] = [1,2,3,4];
// How to write it 2
let strings:Array<string> = ['1','2','3'];

function

/** *  function  *  Function type : Function parameter type 、 return type  *  Ordinary function :function  Function name ( Shape parameter 1: type  =  The default value is , Shape parameter 2: type  =  The default value is , Shape parameter 3: type  =  The default value is ): return type {} *  Arrow function :function  Function name ( Shape parameter 1: type  =  The default value is , Shape parameter 2: type  =  The default value is , Shape parameter 3: type  =  The default value is ): return type =>{} * *  Uniformly define the function format : When the types of functions are consistent , Writing more than one will make the code redundant , Therefore, the format of the function needs to be defined uniformly  * *  If there is no return value type , Should use the void *  Situation 1 : Function didn't write return *  Situation two : Only written. return, No specific return value  *  Situation three :return  The return is undefined * *  Function optional parameters : Parameters can be transferred or not  !! Mandatory parameters cannot follow optional parameters  * fucntion slice(a?:number,b?number) * */
// Ordinary function 
function add1(num1: number, num2: number): number {
    
    return num1 + num2
  }
// Arrow function 
const add2 = (a: number =100, b: number = 100): number =>{
    
    return a + b
  }
// Define a function type uniformly 
type Fn =  (n1:number,n2:number) => number ;
const add3 : Fn = (a,b)=>{
    return a+b }

//============================ The return value is void============
// The return value is void
function greet(name:string= "1234"):void{
    
 console.log("hello",name);
}
//  If you don't write anything , here ,add  The return value type of the function is : void
const add4 = () => {
    }

//  If return Then I don't write anything , here ,add  The return value type of the function is : void
const add5 = () => {
     return }

const add6 = (): void => {
    
  //  here , Back to  undefined  yes  JS  A value of 
  return undefined
}
//  This way of writing is to explicitly specify that the return value type of the function is  void, Same as the return value type not specified above 
const add7 = (): void => {
    }

//  Mandatory parameters cannot follow optional parameters   Don't write like this !!.
// function mySlice(start?:number,end:number){}

object type

/** *  object type  * const  Object name  = { *  Property name 1: type 1, *  Property name 2?: type 2, *  Method name 1( Shape parameter 1:  type 1, Shape parameter 2:  type 2):  return type , *  Method name 2:( Shape parameter 1:  type 1, Shape parameter 2:  type 2) =>  return type  * } = {  Property name 1:  value 1, Property name 2: value 2 } */
// Create type aliases 
type Person = {
    
    name:string,
    age:number,
    sayHi():void
}
// Use the type alias as the type of the object 
let person:Person={
    
    name:"xiaohua",
    age:18,
    sayHi(){
    }
}

Interface

/** *  Interface : When an object type is used more than once , There are two ways to describe the types of objects , To achieve reuse : * 1. Type the alias :type * 2. Interface :interface *  grammar :interface  The interface name { attribute 1: type 1, attribute 2: type 2, attribute 3: type 3} * * * type And interface The difference between  * -  The same thing : You can assign types to objects  * -  Difference : * -  Interface : Only type can be specified for an object ,【 Inherit 】 * -  Type the alias : You can not only specify the type of object , You can also be right about 【 Any type 】 Specify alias  *  First of all interface, After that type, Recommended type * *  Interface inheritance  *  If two interfaces have the same properties or methods , Can be 【 Public properties or methods are extracted , Reuse through inheritance 】 * interface  Interface 2 extends  Interface 1{ *  attribute 1: type 1 // Interface 2 The unique type of  * } */
// Use interface Declare interface 
interface IGoodItem{
    
    name:string,
    age:number,
    func:()=>string,
    func1():string
}
// Use the interface name as the variable type 
const good1:IGoodItem = {
    
    name:" floret ",
    age:18,
    func:function(){
    
        return "123"
    },
    func1:()=>{
    
        return "124"
    }
}

//============= Interface inheritance =============
interface a {
    
    x:number,
    y:number
}
//  Use  extends( Inherit ) Keyword implements the interface 
interface b extends a {
    
    z:number
}
//b Inherited a, That explains. b Have the a All properties and methods of 

Tuples

/** Don't understand, ; *  Tuples : It's a special kind of array , The special point is the following two points  * -  It stipulates the number of elements  * -  It specifies the data type corresponding to a specific index  * */
 function useState(n: number): [number, (number)=>void] {
    
    const setN = (n1) => {
    
        n = n1
    }
    return [n, setN]
}

const [num1 ,setNum] = useState(10)

Literal type

/** *  Literal type  *  effect : Often used with union types  * */
//str1, It's a variable , Its value can be any character , So the type is string
//str2 Is a constant , His value cannot change , Can only be "Hello TS", So his type is "Hello TS",
//  Well, here "Hello TS" It's a literal type , In other words, a specific string can also be used as  TS  The type of 
let str1:string ="hello";
const str2 ="Hello TS";
// Matching joint type 
type Gender = 'girl' | 'boy'
//  Declare a type , His value   yes  'girl'  Or is it  'boy'
let g1: Gender = 'girl' //  correct 
let g2: Gender = 'boy' //  correct 
// let g3: Gender = 'man' //  error 

/** *  enumeration : Be similar to 【 Literal type + Joint type 】, To describe a value  * enum  Enum name { Value for 1, Value for 2...} *  Usage mode : Enum name . Value for 1 *  Be careful : * 1. Generally, enumeration names begin with uppercase letters  * 2. Multiple values in the enumeration are marked with commas , Division  * 3. After defining the enumeration , Directly use enumeration names as type annotations  * *  Enumeration types are divided into : Numeric enumeration and string enumeration  * -  Numerical enumeration : The default is 0 Start self increasing value , You can also initialize values for members in the enumeration  */
enum Eunm1 {
    up,down,left,right};
Eunm1.up;

//  Numerical enumeration   Custom initial value 
enum Direction1 {
     Up = 10, Down, Left, Right };// Down -> 11、Left -> 12、Right -> 13
enum Direction2 {
     Up = 2, Down = 3, Left = 8, Right = 16 }

//  String Enum ( Each member must have an initial value )
enum Direction {
    
    Up = 'UP',
    Down = 'DOWN',
    Left = 'LEFT',
    Right = 'RIGHT'
  }

any

/** * any: Any of the , Remove type restrictions  *  Use scenarios : * -  function  * -  Come on “ avoid ” Writing is long 、 Very complex type  * -  Declared variables do not provide types or default values  * -  When defining a function , Parameter does not give type  * */





原网站

版权声明
本文为[Crisp bamboo book pavilion under the moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050607511546.html