TypeScript接口

382 阅读2分钟

接口

  • 接口一方面可以在面向对象编程中表示为行为的抽象,另外可以用来描述对象的形状
  • 接口就是把一些类中共有的属性和方法抽象出来,可以用来约束实现此接口的类
  • 一个类可以继承另一个类并实现多个接口
  • 接口像插件一样是用来增强类的,而抽象类是具体类的抽象概念
  • 一个类可以实现多个接口,一个接口也可以被多个类实现,一个类的可以有多个子类,但只能有一个父类
  • interface中可以用分号或者逗号分隔每一项,也可以什么都不加

对象的形状

 interface Point{
     x:number
     y:number
 }
 let point:Point = {x:0,y:0}

行为的抽象

interface Speakable{
   speak():void;
}
interface Eatable{
   eat():void
}
//一个类可以实现多个接口
class Person implements Speakable,Eatable{
   speak(){
       console.log('Person说话');
   }
   eat(){}
}
class TangDuck implements Speakable{
   speak(){
       console.log('TangDuck说话');
   }
   eat(){}
}

任意属性

  • 无法预先知道有哪些新的属性的时候,可以使用 [propName:string]:any,propName名字是任意的
interface Person {
    [propName: string]: any;
  }

  let p1:Person = {
    id:1,
    name:'xiuli',
    age:10,
    number:10,
    money:'100000000'
  }

接口的继承

  • 一个接口可以继承自另外一个接口
interface Speakable {
    speak(): void
}
interface SpeakChinese extends Speakable {
    speakChinese(): void
}
class Person implements SpeakChinese {
    speak() {
        console.log('Person')
    }
    speakChinese() {
        console.log('speakChinese')
    }
}

readonly

  • readonly定义只读属性可以避免由于多人协作或者项目较为复杂等因素造成对象的值被重写
interface Person{
  readonly id:number;
  name:string
}
let tom:Person = {
  id :1,
  name:'xiuli'
}
//   tom.id = 1;//报错 只读属性

函数类型接口

  • 对方法传入对参数和返回值进行约束
interface discount{
	(price:number):number
}
let cost:discount = function(price:number):number{
    return price * .8;
}
console.log(cost(1))

可索引接口

  • 对数组和对象进行约束
interface UserInterface {
      [index: number]: string
  }
  let arr:UserInterface = ['1','2','3'];//key为0,1,2是number,值为string

  let obj:UserInterface = {
      1:'1',
      2:'2'
  }

类接口

  • 可以用接口来装饰类
interface Speakable {
    name: string;
    speak(words: string): void
}
class Dog implements Speakable {
    name!: string;
    speak(words:string) {
        console.log(words);
    }
}
let dog = new Dog();
dog.speak('汪汪汪');

构造函数的类型

  • TypeScript中,我们可以用interface来描述类
  • 同时也可以使用interface里特殊的new()关键字来描述类的构造函数类型
class Animal {
	constructor(public name:string){
	}
}
//不加new是修饰函数的,加new是修饰类的
interface WithNameClass{
	new(name:string):Animal
}
function createAnimal(clazz:WithNameClass,name:string){
	return new clazz(name);
}
let a = createAnimal(Animal,'dog')
console.log(a.name)