ES6 目标(Node v4+)中的 async/await 支持
🌐 async/await support in ES6 targets (Node v4+)
TypeScript 现在支持异步函数,前提是引擎本身原生支持 ES6 生成器,例如 Node v4 及以上版本。异步函数使用 async 关键字作为前缀;await 会暂停执行直到异步函数返回的 Promise 被解决,并从返回的 Promise 中获取值。
🌐 TypeScript now supports asynchronous functions for engines that have native support for ES6 generators, e.g. Node v4 and above.
Asynchronous functions are prefixed with the async keyword;
await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned.
示例
🌐 Example
在以下示例中,每个输入元素将以 400 毫秒的延迟逐个打印:
🌐 In the following example, each input element will be printed out one at a time with a 400ms delay:
ts"use strict";// printDelayed is a 'Promise<void>'async function printDelayed(elements: string[]) {for (const element of elements) {await delay(400);console.log(element);}}async function delay(milliseconds: number) {return new Promise<void>((resolve) => {setTimeout(resolve, milliseconds);});}printDelayed(["Hello", "beautiful", "asynchronous", "world"]).then(() => {console.log();console.log("Printed every element!");});
更多信息请参见 异步函数参考 参考。
🌐 For more information see async function reference reference.
支持 --target ES6 与 --module
🌐 Support for --target ES6 with --module
TypeScript 1.7 在 module 选项的可用选项列表中添加了 ES6,并允许你在以 ES6 为目标时指定模块输出。这为在特定运行环境中精确定位所需功能提供了更大的灵活性。
🌐 TypeScript 1.7 adds ES6 to the list of options available for the module option and allows you to specify the module output when targeting ES6.
This provides more flexibility to target exactly the features you want in specific runtimes.
示例
🌐 Example
{"": {"": "amd","": "es6"}}
this-typing
从方法返回当前对象(即 this)以创建流式 API是一种常见模式。例如,考虑以下 BasicCalculator 模块:
🌐 It is a common pattern to return the current object (i.e. this) from a method to create fluent-style APIs.
For instance, consider the following BasicCalculator module:
tsexport default class BasicCalculator {public constructor(protected value: number = 0) {}public currentValue(): number {return this.value;}public add(operand: number) {this.value += operand;return this;}public subtract(operand: number) {this.value -= operand;return this;}public multiply(operand: number) {this.value *= operand;return this;}public divide(operand: number) {this.value /= operand;return this;}}
用户可以将 2 * 5 + 1 表示为
🌐 A user could express 2 * 5 + 1 as
tsimport calc from "./BasicCalculator";let v = new calc(2).multiply(5).add(1).currentValue();
这通常会开辟出非常优雅的代码编写方式;然而,对于想要从 BasicCalculator 扩展的类来说,这存在一个问题。想象一下用户想要开始编写一个 ScientificCalculator:
🌐 This often opens up very elegant ways of writing code; however, there was a problem for classes that wanted to extend from BasicCalculator.
Imagine a user wanted to start writing a ScientificCalculator:
tsimport BasicCalculator from "./BasicCalculator";export default class ScientificCalculator extends BasicCalculator {public constructor(value = 0) {super(value);}public square() {this.value = this.value ** 2;return this;}public sin() {this.value = Math.sin(this.value);return this;}}
因为 TypeScript 过去会为 BasicCalculator 中每个返回 this 的方法推断类型 BasicCalculator,所以在使用 BasicCalculator 方法时,类型系统会忘记它具有 ScientificCalculator。
🌐 Because TypeScript used to infer the type BasicCalculator for each method in BasicCalculator that returned this, the type system would forget that it had ScientificCalculator whenever using a BasicCalculator method.
例如:
🌐 For instance:
tsimport calc from "./ScientificCalculator";let v = new calc(0.5).square().divide(2).sin() // Error: 'BasicCalculator' has no 'sin' method..currentValue();
情况已经不再如此——TypeScript 现在会在类的实例方法内部推断 this 为一种称为 this 的特殊类型。
this 类型的写法如下,基本意思是“方法调用中点左侧的类型”。
🌐 This is no longer the case - TypeScript now infers this to have a special type called this whenever inside an instance method of a class.
The this type is written as so, and basically means “the type of the left side of the dot in a method call”.
this 类型在描述使用混入式模式来描述继承的库(例如 Ember.js)时,与交叉类型也很有用:
🌐 The this type is also useful with intersection types in describing libraries (e.g. Ember.js) that use mixin-style patterns to describe inheritance:
tsinterface MyType {extend<T>(other: T): this & T;}
ES7 幂运算运算符
🌐 ES7 exponentiation operator
TypeScript 1.7 支持即将到来的 ES7/ES2016 指数运算符:** 和 **=。
这些运算符将在输出中使用 Math.pow 转换为 ES3/ES5。
🌐 TypeScript 1.7 supports upcoming ES7/ES2016 exponentiation operators: ** and **=.
The operators will be transformed in the output to ES3/ES5 using Math.pow.
示例
🌐 Example
tsvar x = 2 ** 3;var y = 10;y **= 2;var z = -(4 ** 3);
将生成以下 JavaScript 输出:
🌐 Will generate the following JavaScript output:
jsvar x = Math.pow(2, 3);var y = 10;y = Math.pow(y, 2);var z = -Math.pow(4, 3);
改进了对解构对象字面量的检查
🌐 Improved checking for destructuring object literal
TypeScript 1.7 使得使用对象字面量或数组字面量初始化器检查解构模式变得不那么死板,更加直观。
🌐 TypeScript 1.7 makes checking of destructuring patterns with an object literal or array literal initializers less rigid and more intuitive.
当对象字面量根据对象绑定模式的隐含类型进行上下文类型化时:
🌐 When an object literal is contextually typed by the implied type of an object binding pattern:
- 对象绑定模式中具有默认值的属性在对象字面量中变为可选。
- 对象绑定模式中,如果属性在对象字面量中没有匹配项,则必须在对象绑定模式中具有默认值,并自动添加到对象字面量类型中。
- 对象字面量中,如果属性在对象绑定模式中没有匹配项,则会导致错误。
当数组字面量由数组绑定模式的隐含类型上下文类型时:
🌐 When an array literal is contextually typed by the implied type of an array binding pattern:
- 数组绑定模式中,如果元素在数组字面量中没有匹配项,则需要在数组绑定模式中指定默认值,并自动将其添加到数组字面量类型中。
示例
🌐 Example
ts// Type of f1 is (arg?: { x?: number, y?: number }) => voidfunction f1({ x = 0, y = 0 } = {}) {}// And can be called as:f1();f1({});f1({ x: 1 });f1({ y: 1 });f1({ x: 1, y: 1 });// Type of f2 is (arg?: (x: number, y?: number) => voidfunction f2({ x, y = 0 } = { x: 0 }) {}f2();f2({}); // Error, x not optionalf2({ x: 1 });f2({ y: 1 }); // Error, x not optionalf2({ x: 1, y: 1 });
支持 ES3 目标平台下的装饰器
🌐 Support for decorators when targeting ES3
在以 ES3 为目标时,现在允许使用装饰器。TypeScript 1.7 移除了 __decorate 辅助程序中对 reduceRight 的 ES5 特定用法。这些更改还以内联方式调用 Object.getOwnPropertyDescriptor 和 Object.defineProperty,以向后兼容的方式允许通过移除前述 Object 方法的各种重复调用来清理 ES5 及以后的输出。
🌐 Decorators are now allowed when targeting ES3.
TypeScript 1.7 removes the ES5-specific use of reduceRight from the __decorate helper.
The changes also inline calls Object.getOwnPropertyDescriptor and Object.defineProperty in a backwards-compatible fashion that allows for a to clean up the emit for ES5 and later by removing various repetitive calls to the aforementioned Object methods.