TypeScript 3.1

元组和数组上的映射类型

🌐 Mapped types on tuples and arrays

在 TypeScript 3.1 中,映射对象类型[1] 对元组和数组的映射现在会生成新的元组/数组,而不是创建一个将 push()pop()length 等成员转换的新类型。例如:

ts
type MapToPromise<T> = { [K in keyof T]: Promise<T[K]> };
type Coordinate = [number, number];
type PromiseCoordinate = MapToPromise<Coordinate>; // [Promise<number>, Promise<number>]

MapToPromise 接受一个类型 T,当该类型是像 Coordinate 这样的元组时,只有数值属性会被转换。
[number, number] 中,有两个以数字命名的属性:01
当给定这样的元组时,MapToPromise 会创建一个新元组,其中 01 属性是原始类型的 Promise
所以最终得到的类型 PromiseCoordinate 的类型是 [Promise<number>, Promise<number>]

函数上的属性声明

🌐 Properties declarations on functions

TypeScript 3.1 提供了在函数声明和通过 const 声明的函数上定义属性的能力,只需在同一作用域内给这些函数的属性赋值即可。 这使我们可以编写规范的 JavaScript 代码,而无需使用 namespace 技巧。 例如:

🌐 TypeScript 3.1 brings the ability to define properties on function declarations and const-declared functions, simply by assigning to properties on these functions in the same scope. This allows us to write canonical JavaScript code without resorting to namespace hacks. For example:

ts
function readImage(path: string, callback: (err: any, image: Image) => void) {
// ...
}
readImage.sync = (path: string) => {
const contents = fs.readFileSync(path);
return decodeImageSync(contents);
};

这里,我们有一个函数 readImage,它以非阻塞异步的方式读取图片。除了 readImage,我们还在 readImage 本身提供了一个方便函数,叫做 readImage.sync

🌐 Here, we have a function readImage which reads an image in a non-blocking asynchronous way. In addition to readImage, we’ve provided a convenience function on readImage itself called readImage.sync.

虽然 ECMAScript 导出通常是提供此功能的更好方式,但这种新的支持使以这种风格编写的代码能够在 TypeScript 中“直接工作”。 此外,这种属性声明的方法允许我们在 React 函数组件(以前称为 SFC)上表达常见的模式,如 defaultPropspropTypes

🌐 While ECMAScript exports are often a better way of providing this functionality, this new support allows code written in this style to “just work” in TypeScript. Additionally, this approach for property declarations allows us to express common patterns like defaultProps and propTypes on React function components (formerly known as SFCs).

ts
export const FooComponent = ({ name }) => <div>Hello! I am {name}</div>;
FooComponent.defaultProps = {
name: "(anonymous)",
};

[1] 更具体地说,像上面形式的同态映射类型。

typesVersions 的版本选择

🌐 Version selection with typesVersions

来自我们社区的反馈以及我们自己的经验表明,在利用最新 TypeScript 功能的同时兼顾使用旧版本的用户是很困难的。TypeScript 引入了一个名为 typesVersions 的新特性,以帮助应对这些情况。

🌐 Feedback from our community, as well as our own experience, has shown us that leveraging the newest TypeScript features while also accommodating users on the older versions are difficult. TypeScript introduces a new feature called typesVersions to help accommodate these scenarios.

你可以在声明文件部分的发布部分阅读相关内容

🌐 You can read about it in the Publishing section of the declaration files section