接口定義
interface Person {
name: string
age: number
}
function print(p: Person) {
console.log(p.name);
console.log(p.age);
}
let persion = {age:10, name:"小明"};
print(person)
類型檢查器不會檢查屬性的順序,只要相應的屬性存在并且類型匹配即可。
可選屬性
interface SquareConfig {
color?: string
width?: number
}
定義可選屬性只需要在屬性后面加個?即可。
只讀屬性
一些對象屬性只能在對象被創(chuàng)建的時候修改屬性的值,可以用readonly指定只讀屬性。
interface Point {
readonly x;
readonly y;
}
readonly和const的區(qū)別主要在于一個是針對變量一個是針對對象的屬性。
屬性檢查
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
// ...
}
let mySquare = createSquare({ colour: "red", width: 100 });
如果一個對象字面量存在任何“目標類型”不包含的屬性時,就會出現(xiàn)報錯。有兩種方式可以繞開報錯。
類型斷言
let mySquare = createSquare({colour: "red", width: 100} as SquareConfig);
索引簽名
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any
}
表示對象可能帶有任意數(shù)量的其他屬性。