官網文檔地址 http://www.typescriptlang.org/docs/index.html
接口
使用readonly還是const,最簡單的方法是詢問您是對變量還是屬性使用它。變量使用const,而屬性使用readonly,有些屬性只有在首次創建對象時纔可以修改。您可以通過將readonly放在屬性名之前來指定這一點
interface Point {
readonly x: number;
readonly y: number;
}
屬性類接口
對json對象的約束,屬性及類型約束
interface LabeledValue {
label: string;// 必須屬性
name?:string;// 可選屬性
}
function printLabel(labeledObj: LabeledValue) {
console.log(labeledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};//該json 屬性應包含接口中的全部屬性。
printLabel(myObj);//該json寫法 屬性應包含接口中的全部屬性並且多於接口中的屬性。
printLabel({size: 10, label: "Size 10 Object"});//該json寫法屬性應包含接口中的全部屬性,與接口一致。
函數類型接口
對方法傳入的參數以及返回值進行約束、
This is like a function declaration with only the parameter list and return type given
interface funcinter{
(name:string,sex:string):string;// 此種接口只能定義一個匿名方法,只給出參數列表及返回值類型
}
var mm:funcinter = function(name1:string,sex2:string):string{// 類型屬性與接口中對應位置類型相同
return "s";
}
可索引接口
針對數組、對象的約束
支持兩種類型的索引簽名:字符串和數字。可以支持這兩種類型的索引器,但是數字索引器返回的類型必須是字符串索引器返回的類型的子類型。這是因爲當使用數字進行索引時,JavaScript實際上會在將其轉換爲對象之前將其轉換爲字符串。這意味着使用100(一個數字)的索引與使用“100”(一個字符串)的索引是一樣的,因此兩者需要保持一致
數組的約束
定義數組
let arr:number[] = [1,2,3]
let arr:Array<number> = [1,2,3]
=============
數組
interface userArr{
[index:number]:string;
}
let uArr:userArr = ['1','2','3'];// 數組值爲string
console.log(uArr[0])// 數組索引下標 爲number
=============
json對象的約束
interface userObj{
[name:string]:string;
}
let userobj:userObj = {"name":"string","name1":"string1"}
類類型接口
對類的約束和抽象類相似
interface entryType{
name:string;
pers(name:string,age:number):void;
perso(sex:string):string;
}
class person implements entryType{
name:string;
constructor(name:string){
this.name=name
}
pers(name: string, age: number): void {// 實現的接口參數也可不傳
throw new Error("Method not implemented.");
}
perso(sex: string): string {
throw new Error("Method not implemented.");
}
}
==========
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) { }
}
擴展接口
接口繼承接口,接口繼承類的話在接口中的實現類中也會將接口繼承的類的屬性和方法當作接口要求在實現類中實現。
interface Shape {
color: string;
}
interface Square extends Shape {// 接口繼承接口
sideLength: number;
}
let square = {} as Square;
square.color = "blue";
square.sideLength = 10;
=====
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {// 接口多繼承,類中沒有多繼承
sideLength: number;
}
let square = {} as Square;
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
=====
class eat {
eatName!:string;
action():void{
console.log('123')
}
}
interface person extends eat{ // 混合類型
age:number;
}
class p implements person { // 混合類型,接口繼承類,接口被類實現,實現類中必須實現接口中所有屬性及方法
action(): void {
throw new Error("Method not implemented.");
}
age: number;
eatName: string;
constructor(age: number,eatName: string){
this.age=age;
this.eatName=eatName;
}
}