Skip to content

Commit

Permalink
bugfix: Fix the types of AbortSignal
Browse files Browse the repository at this point in the history
node-fetch#1287 has the unintended consequence of breaking the types of `AbortSignal`. This fixes it.

The [`AbortSignal` definition from `node-fetch`](https://github.com/node-fetch/node-fetch/blob/bcfb71c7d10da252280d13818daab6925e12c368/%40types/index.d.ts#L14-L19) is different from the [node's one](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/globals.d.ts#L59-L65).

This wasn't an issue before because the dom types were imported and were extending the nodejs types with the event listener methods, but that's not the case anymore.

The issue can be reproduce with the following steps:
```
mkdir test && cd test
npm i node-fetch @types/node typescript
touch test.ts
touch tsconfig.json
```

with the `tsconfig.json`:
```json
{
  "include": ["test.ts"],
  "compilerOptions": {
    "lib": ["es2022"],
    "module": "es2022",
    "target": "es2022",
    "skipLibCheck": true,
    "moduleResolution": "node"
  }
}
```

and the test.ts (taken from the README):
```ts
import fetch, { AbortError } from "node-fetch";

const controller = new AbortController();
const timeout = setTimeout(() => {
  controller.abort();
}, 150);

try {
  const response = await fetch("https://example.com", {
    signal: controller.signal,
  });
  const data = await response.json();
} catch (error) {
  if (error instanceof AbortError) {
    console.log("request was aborted");
  }
} finally {
  clearTimeout(timeout);
}
```

Running `npx tsc --project ./tsconfig.json` will show
```
test.ts:10:5 - error TS2739: Type 'AbortSignal' is missing the following properties from type 'AbortSignal': addEventListener, removeEventListener

10     signal: controller.signal,
       ~~~~~~

  node_modules/node-fetch/@types/index.d.ts:91:2
    91  signal?: AbortSignal | null;
        ~~~~~~
    The expected type comes from property 'signal' which is declared here on type 'RequestInit'


Found 1 error in test.ts:10
```
  • Loading branch information
mathieudutour committed Aug 31, 2022
1 parent 6f72caa commit 4b13f84
Showing 1 changed file with 0 additions and 3 deletions.
3 changes: 0 additions & 3 deletions @types/index.d.ts
Expand Up @@ -13,9 +13,6 @@ import {

type AbortSignal = {
readonly aborted: boolean;

addEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void;
removeEventListener: (type: 'abort', listener: (this: AbortSignal) => void) => void;
};

export type HeadersInit = Headers | Record<string, string> | Iterable<readonly [string, string]> | Iterable<Iterable<string>>;
Expand Down

0 comments on commit 4b13f84

Please sign in to comment.