Shyno
Don't be shy,no problem!

    假如我现在需要批量生产一批对象,这些对象有相同的属性,并且对应属性值的数据类型一致.该怎么去做?

    在ts中,因为要检验数据类型,所以必须对每个变量进行规范,自然也提供了一种批量规范的功能.这个功能就是接口.

比如下图就是接口的使用:

结合上图我们对接口进行简单的分析.

 

一、基本使用.

编写接口

interface+接口名 {

       属性名:数据类型;

      属性名:数据类型;

}

使用接口

var/let/const 变量名:接口名={

    属性名:属性值

}

注意:

    1.接口编写完就相当于一种自定义的数据类型,它限制了特定属性名的值的数据类型.

    2.在对象接入接口的时候直接':接口名'使用.但是,对象的属性值必须符合数据类型,不然报错.

   3.数据类型可以是一个有返回值的函数,调用接口的时候,也必须是有返回值的函数

interface test{
    aname:string;
    age:number;
    sex:()=>string
}

const myTest:test={
    aname:'1',
    age:1,
    sex:()=>'a'
}

 

 

 

二、特殊属性接口

基本使用里面我们说了确定属性,即属性名和属性值直接写明了.接下来说一下特殊属性.

1.可选属性.(调用可少)

接口中写了这个属性,但我调用的时候不一定用.

interface test{
    aname:string;
    age:number;
    sex?:string;
}
const i:test={
    aname:'shyno',
    age:18,
}
const you:test={
    aname:'秀吉',
    age:18,
    sex:'秀吉'
}

2.任意属性(调用可多)

在你这个接口规定的几个属性基础下面,我可能还会多几个属性

interface test{
    aname:string;
    age:number;
    sex?:string;
    [propName: string]:any;
}
const i:test={
    aname:'shyno',
    age:18,
    test:1,
    test1:'1'
}
const you:test={
    aname:'秀吉',
    age:18,
    sex:'秀吉',
    test:undefined
}

其中接口中

[propName: string]:any;

string是规定的属性数据类型,设置成number之后属性名是可以用数值的.并且只能是string和number.

然后,如果我们修改了接口任意属性的数据类型,连接口的确定数据类型都会报错,鼠标移入就会发现它的报错和test一样.

反复试验发现,任意属性的数据类型同时限制了接口的可选属性和确定属性.也就是说可选属性和确认属性的的数据类型必须是任意属性的子属性.所以任意属性的数据类型设置的时候要考虑清楚

3.只读属性.

ts对数据类型的限制只是限制非同类型的数据操作,并不是不让其操作.但是只读属性就可以限制程序员对其进行操作

interface test{
    readonly id:number,
    aname:string;
    age:number;
    sex?:string;
    [propName: string]:any;
}


const i:test={
    id:2,
    aname:'shyno',
    age:18,
    test:1,
    test1:'1'
}

注意:只读属性也可以是可选属性

interface test{
    readonly id?:number,
    aname:string;
    age:number;
    sex?:string;
    [propName: string]:any;
}
const i:test={
    aname:'shyno',
    age:18,
    test:1,
    test1:'1'
}

 

三、函数接口

除了限制对象,接口还可以限制函数

interface test{
   (param1:string,param2:number):any
}

let myTest:test=function(param1,param2){
    return (param1+param2)
}

比如这样就可以限制参数数据类型和返回值数据类型

 

四、联合类型接口

假如某个元素有多重数据类型可能,这时候就得用联合类型

interface test{
    aname:string;
    age:number;
    sex:string[] | string | (()=>string);
}

const myTest:test={
    aname:'1',
    age:1+1,
    sex:()=>'a'
}
const myTest1:test={
    aname:'1',
    age:1+1,
    sex:'a'
}
const myTest2:test={
    aname:'1',
    age:1+1,
    sex:['a','b']
}

 

五、接口继承

假如我现在已经有一到两个接口了,我接下来想把这两个接口整合或者说合并到第三个接口的时候,就可以用继承.多接口继承的时候,多个接口之间用逗号隔开

interface test{
    age:number;   
}
interface test1{
    aname:string;  
}
interface test2 extends test,test1 {
    sex:string[] | string | (()=>string);
}

const myTest2:test2={
    aname:'1',
    age:1+1,
    sex:['a','b']
}

 

以上,差不多就是接口的所有用法了.接口还是主要服务于ts的数据类型规范的,灵活使用就行.

 

posted on 2020-08-04 14:59  Shyno  阅读(277)  评论(0编辑  收藏  举报