Skip to content

isGenerator

Checks if a value is a generator object (the result of calling a function*).

Distinct from isGeneratorFunction: this predicate targets the instance produced by calling a generator function, not the function itself.

Available since v2.0.3

import { isGenerator } from '@helpers4/type';
isGenerator(value: unknown): value is Generator<unknown, unknown, unknown>
ParameterTypeDescription
valueunknownThe value to check

value is Generator<unknown, unknown, unknown> — true if value is a Generator instance

Distinguish a generator instance from its function

Section titled “Distinguish a generator instance from its function”

isGenerator targets the object returned by calling a function*, not the function itself.

function* counter() { yield 1; yield 2; }
isGenerator(counter())  // => true   (instance)
isGenerator(counter)    // => false  (function)
isGenerator([1, 2])     // => false

Narrows the type to Generator so you can call .next() and .return().

function* gen() { yield 1; yield 2; }
const value: unknown = gen();
if (isGenerator(value)) {
  const { value: v, done } = value.next();
  // v: unknown, done: boolean | undefined
}

View source on GitHub