如何在 TypeScript 中使用 stage 3 特性?

How to use stage 3 features in TypeScript?

Array.prototype.at() 目前是 stage 3 proposal,我尝试在我的 tsconfig.json 中设置 "lib": ["ESNext"],但我仍然得到:

Property 'at' does not exist on type 'number[]'.

那么如何在 TypeScript 中使用 Array.prototype.at()

概括地说,如何在 TypeScript 中使用第 3 阶段的功能?

P.S。 typescript 版本为 v4.3.5.

无法在 Typescript 中使用第 3 阶段的功能。不是全部。这通常取决于功能。诸如可选链接之类的东西需要 Typescript 的语法更新。

关于 Array.prototype.at,ESNext 的 lib.d.ts 文件可能未针对此类功能进行更新。

因此,您应该在您的项目中创建一个新的 .d.ts 文件,并使用 module augmentation to extend the Array declaration and add correct interfaces for Array.prototype.at. You can look here 查看几个如何实现 lib.es<year>.d.ts 的示例。

例如https://github.com/microsoft/TypeScript/blob/main/lib/lib.es2019.array.d.ts#L58

当然,创建新的 .d.ts 功能不会填充您的代码以添加 Array.prototype.at(如果您的环境不可用)。你仍然需要一个 polyfill 系统,比如带有 core-js 的 Babel。

目前,Array.prototype.at()支持hasn't landed in TypeScript. To use it now, we need to install @types/proposal-relative-indexing-method and include the corresponding polyfill

如果 TypeScript 尚不支持其他第 3 阶段的功能,则相同的步骤适用于这些功能。