TypeScript 1.7
在下面的例子中, 输入的内容将会延时 200 毫秒逐个打印:
查看 Async Functions 一文了解更多.
支持同时使用 —target ES6 和 —module
TypeScript 1.7 将 ES6
添加到了 —module
选项支持的选项的列表, 当编译到 ES6
时允许指定模块类型. 这让使用具体运行时中你需要的特性更加灵活.
{
"compilerOptions": {
"module": "amd",
"target": "es6"
}
}
在方法中返回当前对象 (也就是 this
) 是一种创建链式 API 的常见方式. 比如, 考虑下面的 BasicCalculator
模块:
export default class BasicCalculator {
public constructor(protected value: number = 0) { }
public currentValue(): number {
return this.value;
}
public add(operand: number) {
this.value += operand;
}
public subtract(operand: number) {
this.value -= operand;
return this;
}
public multiply(operand: number) {
return this;
}
public divide(operand: number) {
this.value /= operand;
return this;
}
}
使用者可以这样表述 2 * 5 + 1
:
import BasicCalculator from "./BasicCalculator";
export default class ScientificCalculator extends BasicCalculator {
public constructor(value = 0) {
super(value);
}
public square() {
return this;
}
public sin() {
this.value = Math.sin(this.value);
return this;
}
}
因为 BasicCalculator
的方法返回了 this
, TypeScript 过去推断的类型是 , 如果在 ScientificCalculator
的实例上调用属于 BasicCalculator
的方法, 类型系统不能很好地处理.
举例来说:
import calc from "./ScientificCalculator";
let v = new calc(0.5)
.square()
.divide(2)
.sin() // Error: 'BasicCalculator' 没有 'sin' 方法.
.currentValue();
这已经不再是问题 - TypeScript 现在在类的实例方法中, 会将 this
推断为一个特殊的叫做 this
的类型. this
类型也就写作 this
, 可以大致理解为 "方法调用时点左边的类型".
this
类型在描述一些使用了 mixin 风格继承的库 (比如 Ember.js) 的交叉类型:
ES7 幂运算符
TypeScript 1.7 支持将在 ES7/ES2016 中增加的: 和
=
. 这些运算符会被转换为 ES3/ES5 中的 Math.pow
.
var x = 2 ** 3;
var y = 10;
y **= 2;
var z = -(4 ** 3);
var x = Math.pow(2, 3);
var y = 10;
y = Math.pow(y, 2);
var z = -(Math.pow(4, 3));
TypeScript 1.7 使对象和数组字面量解构初始值的检查更加直观和自然.
当一个对象字面量通过与之对应的对象解构绑定推断类型时:
- 对象解构绑定中有默认值的属性对于对象字面量来说可选.
- 对象解构绑定中的属性如果在对象字面量中没有匹配的值, 则该属性必须有默认值, 并且会被添加到对象字面量的类型中.
数组解构绑定中的元素如果在数组字面量中没有匹配的值, 则该元素必须有默认值, 并且会被添加到数组字面量的类型中.
装饰器 (decorators) 支持的编译目标版本增加 ES3
装饰器现在可以编译到 ES3. TypeScript 1.7 在 __decorate
函数中移除了 ES5 中增加的 reduceRight
. 相关改动也内联了对 Object.getOwnPropertyDescriptor
和 Object.defineProperty
的调用, 并向后兼容, 使 ES5 的输出可以消除前面提到的 方法的重复[1].