我在打字稿设置中将目标设置为'es3'。
{
"compilerOptions": {
"target": "es3",
"outDir": "dist"
}
}
我写了'foreach'语法。
const array: string[] = ['hi', 'hello'];
array.forEach(element => {
console.log(element);
});
我编译了这段代码。 获得了以下结果。
var array = ['hi', 'hello'];
array.forEach(function (element) {
console.log(element);
});
为什么'foreach'语法不能用es3编译?
答案 0 :(得分:3)
在TypeScript中永远不会将方法转换为其他形式。如果您在TypeScript中调用.someMethod()
,生成的JavaScript也会调用.someMethod()
,即使实际上没有这样的方法也是如此。相反,for-of
语法将为您提供与ES3兼容的代码。
for (const item of []) { }
这会给你:
for (var _i = 0, _a = []; _i < _a.length; _i++) {
var item = _a[_i];
}
不幸的是,TS没有显示您没有.forEach
的错误,这是因为lib.d.ts包含每个ES5定义的类型,并认为您拥有它们。 (有关详细信息,请参阅Microsoft/TypeScript#2410)