首页 > 解决方案 > 具有收益返回的静态生成器函数的正确打字稿语法是什么?

问题描述

我正在尝试在使用生成器/收益模式的类上编写静态函数。有人可以给我一个方法签名语法的代码示例吗?具体来说,我正在尝试编写一个斐波那契生成器,但任何数字生成器都可以。

class Mathy {
    static yieldFibonacci(maxValue: number = Number.POSITIVE_INFINITY): IterableIterator<number> {
        let current = 0
        let next = 1
        while (next < maxValue) {
            yield next
            [(current, next)] = [next, current + next]
        }
    }
}

标签: javascripttypescript

解决方案


class Mathy {
    static *yieldFibonacci(maxValue: number = Number.POSITIVE_INFINITY): IterableIterator<number> {
        let current = 0
        let next = 1
        while (next < maxValue) {
            yield next
            ;[current, next] = [next, current + next]
        }
    }
}

推荐阅读