エンジニアとしての市場価値を測りませんか?PR

企業からあなたに合ったオリジナルのスカウトを受け取って、市場価値を測りましょう

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

TypeScript で fetch したものを async iterate できるようにする

Last updated at Posted at 2025-03-19

TypeScript 初心者ですがちょっとハマったので fetch したものを async iterate (async wait) する方法を書いておきます。

まず、具体的な問題はReadableStream<string>オブジェクトを async wait で async iterate しようとすると "Type 'ReadableStream' is not an array type or a string type." というエラーが出てしまう、というものです。

なお環境は ts-node v10.9.2 で fetch を使うために以下の設定をしています。

{
  "compilerOptions": {
    "lib": ["ESNext", "DOM"]
  }
}

どうも原因は ReadableStream<string>async wait に必要な [Symbol.asyncIterator] を実装しているのに TypeScript 側で AsyncIterable<string> を継承していないことにあるようで、必要だったのは as unknown as AsyncIterable<string> でした。

export async function fetchStream(url: string, method:string = 'GET'): Promise<AsyncIterable<string>> {
  const res = await fetch(url, { method: method } )
  if(res.status !== 200 || !res.body) return null
  return (res.body.pipeThrough(new TextDecoderStream()) as unknown as AsyncIterable<string>)
}

export async function main() {
  const stream = await fetchStream('https://triple-underscore.github.io/rfc-others/RFC2616-ja.html')
  if(!stream) return;
  for await (const chunk of stream) {
    console.log("chunk: " + chunk)
  }
}

main();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Comments

No comments

Let's comment your feelings that are more than good

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details

Being held Article posting campaign

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address