TypeScript显式生成器返回类型要求return传参,如何消除无参调用报错?
TypeScript生成器函数类型报错问题解决
我编写了一个作为字符串累加消费者的生成器函数:
function *concatStrings(): Generator<void, string, string> { let result = ''; try { while (true) { const data = yield; result += data; } } finally { return result; } } const g = concatStrings(); g.next(); g.next('abc'); const r = g.return(); console.log(r);
这段代码运行正常,但TypeScript会报错:
Expected 1 arguments, but got 0.ts(2554)
lib.es2015.generator.d.ts(26, 12): An argument for 'value' was not provided.
请问如何修改代码,既能让TypeScript不再报错,又能保留正确的类型?
解决方案
方案1:调整生成器泛型参数,允许首次next()不传参
TypeScript中Generator<T, R, N>的第三个泛型参数N定义了传给next()的参数类型。原代码中N设为string,导致首次调用next()必须传字符串,但生成器首次调用next()时不需要传参(此时还没有yield表达式接收值)。
修改泛型参数为string | undefined,同时在函数内部过滤掉undefined值:
function *concatStrings(): Generator<void, string, string | undefined> { let result = ''; try { while (true) { const data = yield; if (data !== undefined) { result += data; } } } finally { return result; } } const g = concatStrings(); g.next(); // 不再报错 g.next('abc'); const r = g.return(); console.log(r); // { value: 'abc', done: true }
方案2:显式给首次next()传undefined
如果不想修改泛型定义,可以在首次调用next()时显式传入undefined,严格符合原类型要求:
function *concatStrings(): Generator<void, string, string> { let result = ''; try { while (true) { const data = yield; result += data; } } finally { return result; } } const g = concatStrings(); g.next(undefined); // 显式传undefined,满足类型要求 g.next('abc'); const r = g.return(); console.log(r);
内容的提问来源于stack exchange,提问作者CMCDragonkai
相关产品推荐
相关产品推荐

