install
安装
> npm install typescript -g
> tsc -v
Version 2.3.2
初始化, 生成tsconfig.json
> tsc --init
compiling and running
新建文件upAndRunning.ts
let foo: string = "hello";
console.log(foo);
编译
> tsc upAndRunning.ts
生成文件upAndRnnning.js
var foo = "hello";
console.log(foo);
运行upAndRnnning.js
> node upAndRnnning.js
强类型
如果我们给foo赋值123
foo = 123;
再编译
> tsc upAndRunning.ts
upAndRunning.ts(4,1): error TS2322: Type '123' is not assignable to type 'string'.
JavaScript 和 TypeScript定义
TypeScript里使用现成的JavaScript代码 .d.tstypes
import * as Util from "util";
console.log(util.format("Hello %s, world!", "king"));
> tsc upAndRunning.ts
upAndRunning.ts(4,23): error TS2307: Cannot find module 'util'.
安装@types/node
> npm install @types/node --save-dev
> tsc upAndRunning.ts
> node upAndRunning.js
封装
面向对象程序的最基本的一个原则就是封装, 这能力将定义数据和对数据一系列操作的功能定义到单一的组件当中. 大多数编程语言为了实现此目提出了类的概念,提供了一种为数据和相关功能定义模板的方式。
class MyClass {
add(x, y) {
return x + y;
}
}
var classInstance = new MyClass();
var result = classInstance.add(1,2);
console.log(`add(1,2) returns ${result}`);
public 和 private
访问限制
class CountClass {
private _count: number;
constructor() {
this._count = 0;
}
countUp() {
this._count ++;
}
getCount() {
return this._count;
}
}
var countInstance = new CountClass() ;
countInstance._count = 17;
> tsc upAndRunning.ts
upAndRunning.ts(14,15): error TS2341: Property '_count' is private and only accessible within class 'CountClass'.
访问限制只是编译时的一种特性, 和最终生成的可访问性和JavaScript无关.