澄清 Typescript 的目标和库设置的功能

Clarification on functionality of Typescript's target and lib settings

当tsconfig.json有以下

"target": "es5",
"lib": [ "es6", "dom", "es2017" ]

它似乎没有将 es2017 构造转换为 es5。例如,以下将在 IE11 上失败:

var foo = [1, 2, 3].includes(1);

这是设计使然还是我缺少 tsconfig.json 中的设置?

您可以在此处查看包含方法的列表浏览器兼容性

这里不支持IE

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

Clarification on functionality of Typescript's target and lib settings

我认为的简化方法是 target 表示 syntax 输出 JavaScript 的内容,lib 表示什么API members 你的 TypeScript 源代码可以使用。这两个问题的答案中有更详细的说明:

...it doesn't seem to convert es2017 constructs to es5... Is this by design or am I missing a setting in tsconfig.json?

你是对的。这是设计使然。 TypeScript 转换为 target 语法;它不会填充 target 中缺少的 API 成员。 Here is a quote 来自 TypeScript 团队核心成员:

I think you're confusing transpilation with auto-polyfilling. TypeScript doesn't automatically polyfill for you like Babel does, but does perform syntactic downleveling (e.g. for arrow functions). If you want to use ES6 runtime prototype methods, I'd simply include an appropriate ES6 polyfill and its accompanying definition file.

如果您的 lib 包含 API 成员(例如 Array.prototype.include),但在 target 运行时中不存在,那么您需要安装提供以下功能的 polyfill那些 API 成员。