您的位置:首页 > 其它

TypeScript的学习历程4

2017-01-17 16:16 459 查看
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的值不能改变了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: