本文参考w3c官网
1.什么是 TypeScript?
是微软开发的语言,是javascript的拓展。
因此现有的 JavaScript 代码可与 TypeScript 一起工作无需任何修改
2.TypeScript安装
有两种安装方法:(生成.ts后缀的文件)
- 通过node.Js包管理器(npm):npm install –g typescript
- 通过与 Visual Studio 2012 继承的 MSI
3.类型批注
Typescript通过类型批注提供静态类型以在编译时启动类型检查。
function Add(left: number, right: number): number {
return left + right;
}
对于基本类型的批注是number, boolean和string。而弱或动态类型的结构则是any类型。
当类型没有给出时,TypeScript编译器利用类型推断以推断类型。如果由于缺乏声明,没有类型可以被推断出,那么它就会默认为是动态的any类型。
4.接口
接口可以作为一个类型。定义一个变量的类型是接口,这个变量就可以使用这个接口里边的属性。
interface Shape {
name: string;
width: number;
height: number;
color?: string;
}
function area(shape : Shape) {
var area = shape.width * shape.height;
return "I'm " + shape.name + " with area " + area + " cm squared";
}
console.log( area( {name: "rectangle", width: 30, height: 15} ) );
console.log( area( {name: "square", width: 30, height: 30, color: "blue"} ) );
5.箭头函数表达式(lambda表达式)
Lambda表达式()=>{something} 或者 ()=>something ,相当于js中的函数,好处是可以自动将函数中的this附加到上下文中。 function() 替换为 () =>。
This的指向相当于:var _this = this;
6.类
TypeScript支持集成了可选的类型批注支持的es6的类。
构造器中的参数是局部变量。
class Shape {
area: number;
color: string;
constructor ( name: string, width: number, height: number ) {
this.area = width * height;
this.color = "pink";
};
shoutout() {
return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
}
}
var square = new Shape("square", 30, 30);
console.log( square.shoutout() );
console.log( 'Area of Shape: ' + square.area );
console.log( 'Name of Shape: ' + square.name );
console.log( 'Color of Shape: ' + square.color );
console.log( 'Width of Shape: ' + square.width );
console.log( 'Height of Shape: ' + square.height );
以上 Shape 类中有两个属性 area 和 color,一个构造器 (constructor()), 一个方法是 shoutout() 。
Public 成员可以在任何地方访问, private 成员只允许在类中访问。
7.继承
继承使用关键字 extends
我们可以继承一个已存在的类并创建一个派生类
class Shape3D extends Shape {
volume: number;
constructor ( public name: string, width: number, height: number, length: number ) {
super( name, width, height );
this.volume = length * this.area;
};
shoutout() {
return "I'm " + this.name + " with a volume of " + this.volume + " cm cube.";
}
superShout() {
return super.shoutout();
}
}
var cube = new Shape3D("cube", 30, 30, 30);
console.log( cube.shoutout() );
console.log( cube.superShout() );
派生类 Shape3D 说明:
- Shape3D 继承了 Shape 类, 也继承了 Shape 类的 color 属性。
- 构造函数中,super 方法调用了基类 Shape 的构造函数 Shape,传递了参数 name, width, 和 height 值。 继承允许我们复用 Shape 类的代码,所以我们可以通过继承 area 属性来计算 this.volume。
- Shape3D 的 shoutout() 方法重写基类的实现。superShout() 方法通过使用 super 关键字直接返回了基类的 shoutout() 方法。
- 其他的代码我们可以通过自己的需求来完成自己想要的功能。