美文网首页
学习typescript - Interfaces

学习typescript - Interfaces

作者: 土豪码农 | 来源:发表于2019-03-22 22:02 被阅读0次

函数入参限制

function fn(name:string,age:number){}

interface函数入参

interface Obj{
    name:string;
    age:number
}

function fn(obj:Obj){
    console.log(obj.name);
    console.log(obj.age);
}

可选属性

interface Obj{
    name?:string;  //非必填
    age:number
}

只读属性

interface Obj{
    readonly name:string; //非必填
    age:number
}

只读数组

const arr: ReadonlyArray <number> = [1,2,3,4];

接口添加索引名称

interface Obj{
    name:string;
    [propName:string]:any  //一般为2种,对象为string,数组为number
}

接口规定类类型 - 属性

interface PersonInterface{
    name:string;
}

class Person implements PersonInterface{
    name:'222'
}

接口规定类类型 - 方法

interface PersonInterface{
    name:string;
    getName()
}

class Person implements PersonInterface{
    name:'222';
    getName(){
        
    }
}

接口间继承

interface AnimalInterface{
    height:number;
    eat()
}
interface PersonInterface extends AnimalInterface{
    name:string;
}
class Person implements PersonInterface{
    name:'222';
    height:180;
    eat(){
        console.log('eat');
    }
}

混合类型,函数拥有属性方法

interface MixType{
    (name:string):string;
    age:number,
    eat()
}

const Person = ():MixType =>{
    const person = <MixType>function(name){
        return name
    };
    person.age = 12;
    person.eat = () =>{
        console.log('eat');
    };
    return person  //得出来的就是一个混合类型的
};

接口继承类

class Animal{
    active:true;
    height:number;
}
interface PersonInterface extends Animal{
    name:string
}
class Person implements PersonInterface{
    //Animal为true就只能是true,如果为类型string之类的就可以按照类型来
    active:true;
    height:180;
    name:'sss';
}

自行回顾

  • 函数入参限制
  • interface函数入参
  • 可选属性
  • 只读属性
  • 只读数组
  • 接口添加索引名称
  • 可选索引类型
  • 接口规定类类型 - 属性
  • 接口规定类类型 - 方法
  • 继承接口
  • 混合类型,函数拥有属性方法
  • 接口继承类

相关文章

网友评论

      本文标题:学习typescript - Interfaces

      本文链接:https://www.haomeiwen.com/subject/gbddvqtx.html