接口的作用
面向对象的编程中,接口是一种规范的定义,定义了行为和动作的规范,在程序设计中,接口起到限制和规范的作用
接口定义了某一批类说需要遵守的规范,接口不关心这些类的内部数据状态,也不关心类里面方法的实现细节,他只规定了这批内里面必须提供的某些方法提供这些方法的类就可以满足实际需要
属性类型接口
1 2 3 4 5 6 7
| function printLabel(info: { label: string }): void { console.log(info); } printLabel("xxx"); printlabel({ name: "xxx" }); printLabel({ label: "xxx" });
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| interface FullName { firstName: string; lastName: string; } function printName(name: FullName) { console.log(name.firstName + " " + name.lastName); } var name = { firstName: "ayase", lastName: "miya", age: 16, }; printName(name); printName({ firstName: "ayase", lastName: "miya" }); printName({ firstName: "ayase", lastName: "miya", age: 16 });
function printInfo(name: FullName) { console.log(name.firstName + " " + name.lastName); console.log(name.age); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| interface FullName { firstName: string; lastName: string; age?: number; } function printInfo(name: FullName) { console.log(name.firstName + " " + name.lastName); console.log(name.age); } printInfo({ firstName: "ayase", lastName: "miya" }); printInfo({ firstName: "ayase", lastName: "miya", age: 16 }); printInfo({ firstName: "ayase", age: 16 });
|
函数类型接口
1 2 3 4 5 6 7
| interface FullName { (firstName: string, lastName: string):string; } var name:FullName = function (firstName:string, lastName:string):string{ return firstName + lastName } console.log(name('ayase', 'miya))
|
可索引接口
1 2 3 4 5 6 7 8 9 10 11
| interface Arr { [index: number]: string; } var arr1: Arr = ["aaa", "bbb"]; var arr2: Arr = [123, "bbb"];
interface Obj { [index: string]: string; } var obj1: Obj = { name: "aaa" };
|
类类型接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| interface Animal { name: string; eat(str: string): void; }
class Dog implements Animal { name: string; constructor(name: string) { this.name = name; } eat() { console.log("吃" + this.name); } } var dog = Dog("饭"); dog.eat();
|
接口的拓展
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| interface Animal { eat(): void; }
interface Person extends Animal { work(): void; }
class Web implements Person { public name: string; constructor(name: name) { this.name = name; } eat() { console.log(this.name + "吃"); } work() { console.log(this.name + "干活"); } }
var web = new Web("Boku");
|