TS1163
A 'yield' expression is only allowed in a generator body.
Broken Code ❌
function* iterateAlphabet() {
const alphabet = Array.from({ length: 26 }, (_value, index) => String.fromCharCode(index + 65));
for (const char of alphabet) {
yield char;
}
}
const alphabetGenerator = iterateAlphabet();
for (const char of alphabetGenerator) {
console.log(yield char);
}Fixed Code ✔️
You have to remove the yield keyword from the for-of loop:
function* iterateAlphabet() {
const alphabet = Array.from({ length: 26 }, (_value, index) => String.fromCharCode(index + 65));
for (const char of alphabet) {
yield char;
}
}
const alphabetGenerator = iterateAlphabet();
for (const char of alphabetGenerator) {
console.log(char);
}Broken Code ❌
async fetchData(address: string, ticker: string) {
let cursor: number | undefined = 0;
while (cursor) {
const query = new URLSearchParams({
cursor: `${cursor}`,
ticker,
limit: '50'
})
const response = await fetch(url);
const payload = await response.json();
const parsed = ResponseSchema.parse(payload);
for (const result of parsed.results) {
yield result;
}
parsed.next_url ? (url = new URL(parsed.next_url)) : (url = undefined);
}
}Solution:
Add the * symbol to define the function as a generator-async function, allowing yield within its body.
Fixed Code ✔️
async *fetchData(address: string, ticker: string) {
let cursor: number | undefined = 0;
while (cursor) {
const query = new URLSearchParams({
cursor: `${cursor}`,
ticker,
limit: '50'
})
const response = await fetch(url);
const payload = await response.json();
const parsed = ResponseSchema.parse(payload);
for (const result of parsed.results) {
yield result;
}
parsed.next_url ? (url = new URL(parsed.next_url)) : (url = undefined);
}
}