作用
在編譯期間,能夠對值的數據結構進行檢查。可以自定義類型。
用法
接口內部寫法
屬性
接口中的屬性分為:必需屬性,可選屬性,只讀屬性,額外屬性
interface Person{ readonly id: number, //只讀屬性 (不允許修改) name: string, //必需屬性 sex?: number, //可選屬性 [key: string]: any //額外屬性 }
let person:Person = {id: 1, name: "蠟筆小新", hobby: "superman"};
person.id = 3453; //會提示只讀屬性不能修改
類型
- 函數類型,主要定義參數列表和返回值
-
可索引類型,具有一個索引簽名;索引簽名分為:數字和字符串。數字是字符串的子類型(因為在編譯的時候,數字會被轉化為字符串)
//函數類型的接口 (只定義參數列表和返回類型) interface SearchFunc { (source: string, subString: string): boolean; }
let mySearch: SearchFunc;
mySearch = function (sour: string, sub: string) {
let result = sour.search(sub);
return result > -1;
}interface StringArray {
[index: number]: string; //索引類型
length: number;
}
let myArray: StringArray;
myArray = ["4654","wfwf","wfewefewf"];
let str: string = myArray[0];
接口在類、接口中的使用
在類中,
類實現接口,接口只描述了類的公共部分。
一個類在實現一個接口時,只對實例部分進行類型檢查。
interface PersonInterface {
say():void;
//[key: string]: any;
}
class Student implements PersonInterface {
name: string;
constructor(name: string){
this.name = name;
}
say() {
console.log("Hi,"+ this.name);
}
}
let student = new Student("傻白");
補充概念
類靜態部分 & 實例部分
靜態部分: contrutor 函數
實例部分
在接口中,
接口與接口之間也可以相互繼承:extends
interface Shape { color: string; } interface PenStroke { PenWidth: number; } interface Square extends Shape, PenStroke { sideLength: number; }
let square = <Square>{color: "df", PenWidth: 346346,sideLength: 45654};
接口繼承類
只繼承類的成員但不包括其實現。如果這個類剛好有private和protected成員,按要實現這個接口的類一定是子類。
class Control { state: any; private type: string; }
interface SelectableControl extends Control {
select() : void;
}class Button extends Control implements SelectableControl {
select() {
console.log(this.state);
}
constructor(state: string) {
super();
this.state = state;
}
}
let button = new Button("按鈕");
console.dir(button);