运行快速上手
在windows终端cmd命令行以管理员身份运行,输入cnpm install -g typescript
进行安装,记得将cnpm下载源切换到淘宝镜像源。然后继续输入tsc -v
查看是否安装成功。出现版本号即表示安装成功。
类型批注
TypeScript 通过类型批注提供静态类型以在编译时启动类型检查。这是可选的,而且可以被忽略而使用 JavaScript 常规的动态类型。
function Add(left: number, right: number): number {
return left + right;
}
对于基本类型的批注是number, bool和string。而弱或动态类型的结构则是any类型。当类型没有给出时,TypeScript编译器利用类型推断以推断类型。如果由于缺乏声明,没有类型可以被推断出,那么它就会默认为是动态的any类型。
class说明
TypeScript支持集成了可选的类型批注支持的ECMAScript 6的类。以下是定义一个类的代码。
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 )