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的值不能改变了
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的值不能改变了
相关文章推荐
- LINUX命令总结
- [置顶] 如何解决eclipse中修改后台代码ctrl+s时总是自动重启服务的问题
- 如何构建自己的python package
- 从今天起做一个努力,快乐的程序员
- C++虚函数在基类中不实现导致的报错
- CI持续集成系列之(九)代码发布脚本模板书写
- MONGO的简单语法,新手实用
- ThinkPHP5.0完全开发手册.【CHM】下载
- ActiveMQ持久化消息的三种方式
- 提升SQLite数据插入效率低、速度慢的方法
- javaweb解决添加和显示时乱码的问题
- 初识Hook技术
- Masonry适配——(7)UITableView中自定义UITableViewCell高度自适应及计算
- LightOJ 1259 Goldbach`s Conjecture
- CentOS卸载系统的OpenJDK
- JFreeChart 中文乱码
- sass笔记(二)
- 以太网基础知识0(UDP和TCP有什么区别)
- 【Usaco2009 gold 】修建道路
- gitbook 简单编译书籍演示