interface Tips{
label:string,
color?:string,
[propName:string]: number | string | undefined
}
var circle:Tips = {
label:"圓形",
radius:3
};
var rectangle:Tips = {
label:"矩形",
width:100,
height:100
}
descLog(circle);
descLog(rectangle);
color?:string
表示它是可選的。物件不僅可以約束物件的結構,還能約束函數。
interface RectangleAreaMethod {
(width: number, height: number): number
}
let func:RectangleAreaMethod = function(w: number, h:number){
return w * h;
}
let func2:(w:number, h:number)=>number = function(w:number, h:number){
return w * h;
}
陣列、字典都是可索引的類型,我們可以透過陣列下標、字典key名稱索引到值。
interface JArray {
[index: number]: string
}
interface JDictionary{
[key: string]: string
}
let arr: JArray = ["a", "b", "c"];
let map: JDictionary = {
"a":"A",
"b":"B"
}
console.log(arr[1]); //b
console.log(map["a"]); //A
今天的內容就先到這邊,明天將會介紹用介面來約束類別!