考虑以下 TS 示例:
fetch("http://localhost:3000/auth", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then((response) => {
// would like to store some information from the response's headers
// like access tokens etc.
// Typescript complains about this iteration (see more info below)
for (var pair of response.headers.entries()) {
console.log(pair[0] + ': ' + pair[1])
}
return response.json()
})
// get the response data etc...
.then((data) => {
console.log(data);
})
// log an error etc...
.catch((error) => {
console.log('ERROR: ', error);
})
通常,这将是有效的,但 Typescript 会抱怨迭代并建议使用编译器选项:
Type 'IterableIterator<[string, string]>' is not an array type or a string type.
Use compiler option '--downlevelIteration' to allow iterating of iterators.
使用有什么缺点--downlevelIteration
吗?是否有另一种无需更改编译器选项即可完成此操作的方法?
谢谢!
ES6 中添加了迭代器(在某些语言中称为枚举器)。它们在 ES5 及更早版本中不存在。在 ES6 之前,只有 iterable 构造Array
或所谓的数组像本机对象。ES6 带来了迭代器和类似的特性for ... of
。当目标低于 ES6 时,您必须使用downlevelIteration
以将 ES6 迭代器代码转换为 ES5 兼容代码(迭代器将更改 do Array
s 并将for ... of
被 ES5 有效语法替换)。如果您除了 TSC 之外没有使用其他转译器,您别无选择,只能启用此标志。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句