看了Anders Hejlsberg大佬的视频-2017:What’s new in TypeScript?2018:What’s new in TypeScript?,感觉typescript好有意思,尝试一下~

上手

首先生成tsconfig.json,使用命令

1
tsc --init

tsconfig.json用来告诉这个目录是一个TypeScript项目,里面可以配置一下编译选项和包含的定义文件等

使用typescript的监控模式,会实时监控项目目录下的文件变化,有变化就会重新编译它

1
tsc -w

编写ts文件

比如下面的ts文件,定义了一个interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// test.ts
interface Person {
name: string;
age: number;
}

class SS {
name: string = '123';
sayHello() {
console.log("hello");
}
}
function lalala(ss: SS) {
console.log(ss.name)
}

使用 tsc test.ts后得到对应的test.js

1
2
3
4
5
6
7
8
9
10
11
12
var SS = /** @class */ (function () {
function SS() {
this.name = '123';
}
SS.prototype.sayHello = function () {
console.log("hello");
};
return SS;
}());
function lalala(ss) {
console.log(ss.name);
}

因为在tsconfig.json可以选择target,默认是es5,

1
2
3
4
5
6
7
{
"compilerOptions": {
/* Basic Options */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
"module": "es2015",
}
}

修改为es6后,代码被编译成下面ES6代码

1
2
3
4
5
6
7
8
9
10
11
12
"use strict";
class SS {
constructor() {
this.name = '123';
}
sayHello() {
console.log("hello");
}
}
function lalala(ss) {
console.log(ss.name);
}