You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript 5.6迭代器类型错误:Generator无法赋值给BuiltinIterator

TypeScript 5.6.0-beta 伪造 window.location 时的迭代器类型错误解决办法

升级TypeScript到5.6.0-beta后,在单元测试中伪造window.location对象时,ancestorOrigins的Symbol.iterator生成器函数出现类型不兼容错误——生成器返回类型void无法匹配内置迭代器要求的undefined。即便更新@types/node到20.16.1,问题依然存在。

相关代码

function getFakeLocation(getCurrentUrl: () => URL): Location {
  return {
    get ancestorOrigins(): DOMStringList {
      return {
        length: 1,
        contains: (origin: string) => {
          // …
        },
        item(index: number) {
          // …
        },
        *[Symbol.iterator]() {
          yield getCurrentUrl().origin;
        },
      };
    },
    assign: (url: string) => {
      // …
    },
    get href() {
      // …
    },
    set href(url: string) {
      //
    },
    // …
  };
}

错误信息

Type '() => Generator<string, void, any>' is not assignable to type '() => BuiltinIterator<string, undefined, any>'.
  Call signature return types 'Generator<string, void, any>' and 'BuiltinIterator<string, undefined, any>' are incompatible.
    The types returned by 'next(...)' are incompatible between these types.
      Type 'IteratorResult<string, void>' is not assignable to type 'IteratorResult<string, undefined>'.
        Type 'IteratorReturnResult<void>' is not assignable to type 'IteratorResult<string, undefined>'.
          Type 'IteratorReturnResult<void>' is not assignable to type 'IteratorReturnResult<undefined>'.
            Type 'void' is not assignable to type 'undefined'.

解决方法

方法1:给生成器显式返回undefined

在生成器函数末尾添加return undefined;,让生成器的返回类型从void变为undefined,匹配内置迭代器的类型要求:

*[Symbol.iterator]() {
  yield getCurrentUrl().origin;
  return undefined;
}

方法2:显式指定迭代器的返回类型

直接给Symbol.iterator函数标注返回类型为Iterator<string>,强制类型匹配:

[Symbol.iterator]: () => Iterator<string> = function* () {
  yield getCurrentUrl().origin;
}

或者在返回的DOMStringList对象上直接标注迭代器的类型:

return {
  length: 1,
  contains: (origin: string) => { /* ... */ },
  item(index: number) { /* ... */ },
  [Symbol.iterator]: function* (): Iterator<string> {
    yield getCurrentUrl().origin;
  },
};

原因说明

TypeScript 5.6.0-beta对内置迭代器的类型检查进行了严格化,之前版本中void和undefined在迭代器返回值场景下被视为兼容,但新版本明确要求内置迭代器的返回值必须是undefined。默认情况下,没有显式return语句的生成器会返回void,因此触发了类型错误。

内容的提问来源于stack exchange,提问作者balu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 08:11:12