Basic use of TypeScript (1)

This chapter mainly talks about the difference between ts and js and some other usages. It is a good choice for novice students who learn ts.

1. Variable declaration (declaration of the basic type of data) . After the variable declaration is completed, if the type is incorrect when reassigning the value, an error will be reported. Here, pay attention to the following

        Declare numeric types   

let num:number = 123

        Declare the string type:

 let str:string = ”123“

        declare boolean type

let b:boolean =true  //只能赋值true或者 false

        declare undefined

 let un:undefined = unidefinde //只能赋值undefined

        Declare data of type null

let nu:null = null //只能赋值null

        Declare any. This is equivalent to turning off the type detection, and no matter how the variable is assigned in the subsequent assignment, it will not prompt

let an:any = "12asda"  //赋值关闭类型检测,没有实际意义。如果赋值时都用any的话,不如直接用js来写代码,这点需要注意!!!

2. Declare the joint type data. The joint type means that when we specify the variable type, we can specify not only one type, but also multiple types.

let arr:number | string = ”123“ //表示即可以赋值number类型的数据也可以赋值string类型的数据

3. Declare data of reference type (array)

        Declare array1,

let arr :number[]=[1,2,3,4]  //arr是变量名称,number是数组里的数据格式,number后面就是我们的数据类型

       Declare array2:

let arr :string[]=[”123“]  //arr是变量名称,string是数组里的数据格式,string后面就是我们的数据类型

. . . . Data types can define various types of data

3. Declare reference type data (object)

let obj:{name:string} ={name:"123"} //对象的key必须是name,value的值得是string,这里声明时规定

This means that the value in our object is only name, and the number and type of data in the object are limited.

 Can be used without restrictions when creating variables

let obj:{name:string,[propName:string]:any}, //对象里面必须要用name:string,其他数据不做限制,包括其他数据的多少和类型

4. Multidimensional data type definition

      Multidimensional data is our array of arrays, array of objects, etc.

        Defining arrays of arrays

let a:number[][]=[[1,]] //number是我们数组里的数据类型,这里定义的是number,如果我们不做限制的话直接用any即可,number后面接的2个空数组,代表着我们是2维数组,数组里面套数组,最里层数组的数据必须是number

        Define the nested object in the array

const ang :{"name":string}[]=[{name:"123"}] //数组里面套对象,对象的key必须是name,value必须是string类型的数据

 5. Data definition of function type

let fn:()=>number=()=>{
    return 123
}//定义一个函数fn,fn规定了返回值number  
let fn=()=>{
    return 123
}  //定义了函数fn,没有规定返回值
let fn(a:number,b:string)=>number=>(1,"123")=>{return 123}
//规定了传入2个参数,第一个参数是number类型的数据,第二个参数是string类型的参数,
同时规定必须要有返回值,返回值必须是number类型的数据

Guess you like

Origin blog.csdn.net/m0_58002043/article/details/130846815