まらんさんのチラ裏

その日暮らしのおじさん

node-fetch で AbortSignal を使おうとすると怒られたのでその回避策メモ

環境

  • node-fetch@2.6.9
  • @types/node-fetch@2.6.2

発生したこと

node-fetch を使っていたらこんな感じで怒られてビルドできなくなってしまった。 node-fetch を 3 系にしてもいいんだけどそれだと esm が強制されちゃうので 2 系でいきたいところ。

$ tsc
src/index.ts:29:11 - error TS2322: Type 'AbortSignal' is not assignable to type 'import("/Users/malan/repos/xxx/functions/node_modules/@types/node-fetch/externals").AbortSignal'.
  Types of property 'onabort' are incompatible.
    Type '((this: AbortSignal, ev: Event) => any) | null' is not assignable to type '((this: AbortSignal, event: any) => any) | null'.
      Type '(this: AbortSignal, ev: Event) => any' is not assignable to type '(this: AbortSignal, event: any) => any'.
        The 'this' types of each signature are incompatible.
          Type 'AbortSignal' is missing the following properties from type 'AbortSignal': reason, throwIfAborted

29           signal: controller.signal as AbortSignal,
             ~~~~~~


Found 1 error in src/index.ts:29

回避策

いろいろソースを見ていたら externals.d.ts に AbortSignal が独自定義されていたのでこいつを直接引っ張ってきて使うという方法で回避。

import fetch from 'node-fetch';
import { AbortSignal } from 'node-fetch/externals';  // add this line

...

await fetch(input, {
    ...init,
    signal: controller.signal as AbortSignal,  // cast
  });

おわり

一応 github の issue にもコメント入れておいた。

github.com