首页 > 解决方案 > 在 TypeScript 中 GeneratorFunction 接口代表什么?

问题描述

function* 声明(function 关键字后跟一个星号)定义了一个生成器函数,它返回一个 Generator 对象。[参考]

但如果我这样做:

const genFn: GeneratorFunction = function* () {};

我得到:

Property '[Symbol.toStringTag]' is missing in type '() => Generator<never, void, unknown>' but required in type 'GeneratorFunction'.ts(2741)
lib.es2015.symbol.wellknown.d.ts(161, 14): '[Symbol.toStringTag]' is declared here.

在 TypeScript 中 GeneratorFunction 接口代表什么?另外,是否有更合适的内置接口来捕获生成器功能?

标签: typescript

解决方案


以下是一般的四个级别的注释。所有这些都将编译没有错误:

// Truly general
const genFnA: Function = function* () {};

// Bit less general
const genFnB: () => Generator = function* () {};

// Exact manual
const genFnC: () => Generator<never, void, unknown> = function* () {};

// Best: Use the inference
const genFnD = function* () {};

推荐阅读