Borislav Hadzhiev
Sun Mar 27 2022·2 min read
Photo by Jenny Marvin
To solve the error "'Yield' expression implicitly results in an 'any' type",
explicitly type the generator function with the Generator
generic, e.g.
function* generator(): Generator<YieldType, ReturnType, AssignmentType> {}
.
Here is an example of how the error occurs.
function* generator() { // ⛔️ Error: 'yield' expression implicitly results in an 'any' type // because its containing generator lacks a return-type annotation.ts(7057) // 👇️ const result: any const result = yield 'hello'; yield 'world'; yield '!'; }
The error occurs because TypeScript is not able to able to infer the type of the
result
variable, because we didn't explicitly set the return type of the
generator function.
result
variable is implicitly typed as any
, which caused the error.A quick way to solve the error is to set the return type of the generator
function to any
.
function* generator(): any { const result = yield 'hello'; yield 'world'; yield '!'; }
Now the result
variable is explicitly typed as any
, so we no longer get the
error. However, this might not be what you want, because any
turns off type
checking.
An alternative approach is to provide a return-type annotation for the generator.
function* generator(): Generator<string, number, string> { // 👇️ const result: string; const result = yield 'hello'; yield 'world'; yield '!'; return 10000; }
The first type we passed to the Generator
generic
is the type of what we want to yield
.
We yield the strings hello
, world
and !
in the example generator.
Generator
generic takes is the return type of the generator function.The third type is the type of values that are assigned by yield expressions.
So the Generator
generic looks something like:
Generator<YieldType, ReturnType, AssignmentType>
.
yield 'hello'
to a variable, so we provided a string
as the third type to the Generator
generic.Now TypeScript knows the type of the result
variable is going to be a string
and it's no longer implicitly typed as any
.
If we try to assign the result of a yield expression that has a type of
number
, we'd get an error.
function* generator(): Generator<string, number, string> { const result = yield 'hello'; // ⛔️ Error: Type 'number' is not assignable to type 'string'.ts(2322) const result2 = yield 100; yield 'world'; yield '!'; return 10000; }
Similarly, if we try to return a value that is not a number, or yield a value that is not a string, we'd get an error.
Here is a complete example of using the generator function.
function* generator(): Generator<string, number, string> { const result = yield 'hello'; yield 'world'; yield '!'; return 10000; } const gen = generator(); console.log(gen.next().value); // 👉️ "hello" console.log(gen.next().value); // 👉️ "world" console.log(gen.next().value); // 👉️ "!" console.log(gen.next().value); // 👉️ 10000 console.log(gen.next().value); // undefined