中拓網(wǎng)絡(luò)科技有限公司北京seo不到首頁不扣費
1. 接口有什么用
通過 interface 定義接口。
檢測對象的屬性,不會去檢查屬性的順序,只要相應(yīng)的屬性存在并且類型也是對的就可以。
interface IPerson {name: string;age: number;
}
function say(person: IPerson): void {console.log(`my name is ${person.name}, and age is ${person.age}`);
}
let me = {name: "funlee",age: 18,
};
say(me); // my name is funlee, and age is 18
2. 可選屬性
屬性后面加一個 ? 符號,表示該屬性可選。
interface IPerson {name: string;age: number;// love 可選love?: string;
}
3. 只讀屬性
屬性名前加 readonly,表示該屬性只讀。
interface IPerson {// name 只讀readonly name: string;age: number;love?: string;
}
let me: IPerson = {name: "funlee",age: 18,
};
// name 不允許被賦值
me.name = "new name"; // error!
4. 函數(shù)接口
接口可以描述函數(shù)類型,它定義了函數(shù)的參數(shù)列表和返回值類型,參數(shù)列表里的每個參數(shù)都需要名字和類型,函數(shù)的參數(shù)名不需要與接口里定義的名字相匹配,只需要類型兼容就可以了。
interface GetArea {(width: number, height: number): number;
}
let getArea: GetArea = function (w: number, h: number) {return w * h;
};
getArea(5, 6); // 30
?5. 繼承接口
一個接口可以繼承多個接口,創(chuàng)建出多個接口的合成接口,如:
interface Shape {color: string;
}
interface PenStroke {penWidth: number;
}
interface Square extends Shape, PenStroke {sideLength;
}
const square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
?6. 混合類型
讓對象同時作為函數(shù)和對象使用,并帶有額外的屬性,如:
interface MixedDemo {(str: string): void;defaultStr: string;
}function foo(): MixedDemo {let x = <MixedDemo>function (str: string) {console.log(str);};x.defaultStr = "Hello, world";return x;
}let c = foo();
c("This is a function"); // 'This is a function'
c.defaultStr; // 'Hello, world'
?