接口就是用代碼描述一個(gè)對(duì)象必須有什么屬性(包括方法)骄噪,但是有沒有其他屬性就不管了
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
// 我們傳入的對(duì)象參數(shù)實(shí)際上會(huì)包含很多屬性蚌铜,但是編譯器只會(huì)檢查那些必需的屬性是否存在,并且其類型是否匹配遮怜。
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
對(duì)象字面量會(huì)被特殊對(duì)待而且會(huì)經(jīng)過(guò) 額外屬性檢查
如果一個(gè)對(duì)象字面量存在任何“目標(biāo)類型”不包含的屬性時(shí),你會(huì)得到一個(gè)錯(cuò)誤
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
printLabel( {size: 10, label: "Size 10 Object"}); // 會(huì)報(bào)錯(cuò)
繞開這些檢查非常簡(jiǎn)單。 最簡(jiǎn)便的方法是使用類型斷言:
printLabel( {size: 10, label: "Size 10 Object"} as LabelledValue);
或者添加一個(gè)字符串索引簽名
interface LabelledValue {
label: string;
[propName: string]: any; //這我們要表示的是LabelledValue可以有任意數(shù)量的屬性
}
可選屬性
interface SquareConfig {
color?: string;
width?: number;
}
只讀屬性
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
TypeScript具有ReadonlyArray<T>類型曙聂,它與Array<T>相似,只是把所有可變方法去掉了鞠鲜,因此可以確保數(shù)組創(chuàng)建后再也不能被修改:
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!
接口描述函數(shù)類型
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
當(dāng)函數(shù)類型有屬性時(shí)
微信圖片_20210224165232.png
類類型
TypeScript也能夠用它來(lái)明確的強(qiáng)制一個(gè)類去符合某種契約
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date; // 類必須含有currentTime屬性
constructor(h: number, m: number) { }
}
繼承接口
interface Animal {
move():void;
}
interface Human extends Animal { // 可繼承多個(gè)宁脊,用逗號(hào)分隔
name: string;
age: number;
}
let simon: Human = {
name: 'simon',
age: 19,
move() {
console.log('我在動(dòng)')
}
}
simon.move() // 我在動(dòng)