Basic use of TypeScript (2)

1. Special data declaration (date, regularization, etc.)

        date

let d:Date=new Date() //声明一个日期对象

        Regular

let reg:RegExp=/\d{6}/  //正则

        Or declare a page element object

let divs:NodeList=document.getElementBtid(“box”) //声明id是box的页面元素对象

2. Interface (this interface is not a back-end interface, it is equivalent to a template of an object, declare a template, and then use this template to generate data according to regulations)

        2.1 Create an interface (the keyword interface declares that this data is a template data)

interface person {
Name:string,moner:number
} //后续我们用这个接口来创建数据时,所创建的数据必须的和这个模板的数据格式,内容一致,比如
//对象里第一个key得是name,value的值必须是string类型的数据,第二个数据的key必须是moner。值必须是number类型的数据

        2.2 Create objects through the interface we created

let arr:person ={name:"123",moner:123} //person是我们定义的接口的名称,(模板名称)

        2.3 Define a readable attribute for the data

interface person {
readonly  Name:string,moner:number
} 
//在我们需要定义为可读的参数前加上readonly 即可将改属性变为可读属性,当我们用这个模板创建好数据后,后续我们如果需要修改这个属性,就会报错。

        2.4 Interface inheritance (multiple interfaces can be combined together, keyword extends )

interface person1 {
Name:string,moner:number
} //创建第一个模板

interface person2 extends person1{
age:number
} //创建第2个模板,这里用extends将第一个模板继承过来。后续我们创建数据时用了person2时,所创建的数据必须芒祖person1和person2所规定的类型,相当于将person1的模板类型加到person2里头去了

3. Literal writing

It is equivalent to specifying which values ​​​​variables must only use

let nu:1|2|3=1  //nu只能赋值1,2,3

4. Enumeration type data declaration

enum gender{ weix, ais ,saca}  //enum是关键字,gender是变量名称,默认第一个枚举的数据是0

        4.1 Get the enumeration value

变量名【“值”】
enum gender{ weix, ais ,saca}
gender[“weix”] //返回0,我们查询的是weix,weix在数据里是排第一个所以返回的是0

        4.2 Get data by serial number

变量名[序号]
enum gender{ weix, ais ,saca}
gender[1]  //ais  ,返回ais,因为数据是从0开始的

5. Generics

        Extensive types, in summary, the type is also used as a variable, and the variable must be passed when using it

generic application

     

Function fn <T>(data:T):T{
Return data
}  //定义了一个函数fn,函数接收一个类型变量t,类型变量t作为我们所接收的形参data上,给data规定类型


fh<number>(100)  //使用fn函数,传入类型number,由于我们的data形参规定的类型是我们传入的类型,我们传入的是number类型,所以实参必须赋值number的类型数据,所以实参赋值100

Guess you like

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