我试图编写一个生成器函数,它将连续返回一对可迭代对象中的前一个和当前值.
function* prevCurrent<T>(iterable: Iterable<T>) {
let head = true
let previous: T
for (const current of iterable) {
if (head) {
previous = current
head = false
continue
}
yield [previous, current]
previous = current
}
}
使用方法如下:
const arr = [1, 2, 3]
for (const pair of prevCurrent(arr)) {
console.log(pair)
}
// [1, 2]
// [2, 3]
然而,在yield
行,TypeScript报告:
Variable 'previous' is used before being assigned.
显然,静态分析没有意识到yield
只能在for-of
的第二次迭代中达到,previous
已经设置.
我可以很容易地通过!
操作员解决这个问题.但是is there an alternative syntax or logic I could use that static analysis would accept?