接口是一系列抽象方法的声明。
定义
TypeScript 接口定义:
interface interface_name {
}
举例
如下定义了一个接口 IPerson,接着定义了一个变量 customer,它的类型是 IPerson。
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
var customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
console.log(customer.firstName)
console.log(customer.lastName)
console.log(customer.sayHi())
接口继承
interface Person {
age:number
}
interface Musician extends Person {
instrument:string
}
var drummer = <Musician>{};
drummer.age = 27
drummer.instrument = "Drums"
console.log("年龄: "+drummer.age)
console.log("喜欢的乐器: "+drummer.instrument)