typescript:接口
function printLabel(labelledObj: { label: string }) { // labelledObj接口名 :{接口里面的值:类型} console.log(labelledObj.label); } let myObj = { size: 10, label: "Size 10 Object" }; //接口 printLabel(myObj); // 使用接口
使用另一种方法编写 接口
interface Lablesss{
lable: string;
}
function printLales(lableObj: Lablesss){
console.log(lableObj.lable);
}
let myObj = { size: 10, lable: "Size 10 object" };
printLales(myObj);
接口的可选属性
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"});
只读属性
可以在属性名前用 readonly来指定只读属性:
interface Point {
readonly x: number;
readonly y: number;
}
构造一个Point。 赋值后, x和y再也不能被改变了。
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // 错误,x的值不能改变了