1.接口初探
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
2.可選屬性
這段代碼寫的很好
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): {color: string; area: number} {
let newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
3.只讀屬性
interface Point {
readonly x: number;
readonly y: number;
}
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!
- 上面代碼的最后一行,可以看到就算把整個(gè)ReadonlyArray賦值到一個(gè)普通數(shù)組也是不可以的。 但是你可以用類型斷言重寫:
a = ro as number[];
4.最簡(jiǎn)單判斷該用readonly還是const的方法是看要把它做為變量使用還是做為一個(gè)屬性。 做為變量使用的話用 const,若做為屬性則使用readonly。
4. 額外的屬性檢查
對(duì)象字面量會(huì)被特殊對(duì)待而且會(huì)經(jīng)過 額外屬性檢查,當(dāng)將它們賦值給變量或作為參數(shù)傳遞的時(shí)候。 如果一個(gè)對(duì)象字面量存在任何“目標(biāo)類型”不包含的屬性時(shí),你會(huì)得到一個(gè)錯(cuò)誤。
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
// ...
}
// error: 'colour' not expected in type 'SquareConfig'
let mySquare = createSquare({ colour: "red", width: 100 });
- 方法一:繞開這些檢查非常簡(jiǎn)單。 最簡(jiǎn)便的方法是使用類型斷言:
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
- 方法二:添加一個(gè)字符串索引簽名
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any;
}
- 還有最后一種跳過這些檢查的方式,這可能會(huì)讓你感到驚訝,它就是將這個(gè)對(duì)象賦值給一個(gè)另一個(gè)變量: 因?yàn)?squareOptions不會(huì)經(jīng)過額外屬性檢查,所以編譯器不會(huì)報(bào)錯(cuò)。
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);
5. 函數(shù)類型
- 可索引的類型
7.類類型
8.繼承接口
9.混合類型
10.繼承接口類