17.TypeScript 接口
接口是一系列抽象方法的声明,是一些方法特征的集合,这些方法都应该是抽象的,需要由具体的类去实现,然后第三方就可以通过这组抽象方法调用,让具体的类执行具体的方法。
接口定义
interface interface_name {
}
例子:
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
let customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
以上示例中,定义了一个接口 IPerson,它有两个属性和一个抽象的方法。接着定义了一个变量 customer,它的类型是 IPerson。
customer 实现了接口 IPerson 的属性和方法。
在接口中使用联合类型
interface RunOptions {
program:string;
commandline:string[]|string|(()=>string);
}
// commandline 是字符串
let options:RunOptions = {program:"test1",commandline:"Hello"};
console.log(options.commandline)
// commandline 是字符串数组
options = {program:"test1",commandline:["Hello","World"]};
console.log(options.commandline[0]);
console.log(options.commandline[1]);
// commandline 是一个函数表达式
options = {program:"test1",commandline:()=>{return "**Hello World**";}};
let fn:any = options.commandline;
console.log(fn());
- 在接口中指定数组的索引值和元素设置为不同类型,索引值可以是数字或字符串
如设置元素为字符串类型,如果使用了其他类型会报错:
interface namelist {
[index:number]:string
}
// 类型一致,正确
var list2:namelist = ["Google","Runoob","Taobao"]
// 报错,元素 1 不是 string 类型
// var list2:namelist = ["Runoob",1,"Taobao"]
继承接口
接口可以通过继承其他接口来扩展自己,Typescript 允许接口继承多个接口。继承使用关键字 extends。
- 单接口继承
Child_interface_name extends super_interface_name
- 多接口继承
继承的各个接口使用逗号 , 分隔
Child_interface_name extends super_interface1_name, super_interface2_name,…,super_interfaceN_name
接口拥有所继承接口的所有能力。
浙公网安备 33010602011771号