3

I'm trying to create a function that wraps fetch from node-fetch by just adding a cookie:

import fetch from 'node-fetch';

const api = (path: string, params: RequestInit) => fetch(
  path, {
    ...(params || {}),
    headers: {
      ...(params?.headers || {}),
      cookie: 'mycookie'
    },
  }
)

I'm getting this error on headers:

(property) RequestInit.headers?: string[][] | Headers | {
    [key: string]: string;
} | undefined
Type '{ cookie: string; append(name: string, value: string): void; delete(name: string): void; get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; } | { ...; } | { ...; }' is not assignable to type 'string[][] | Headers | { [key: string]: string; } | undefined'.
  Type '{ cookie: string; append(name: string, value: string): void; delete(name: string): void; get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; }' is not assignable to type 'string[][] | Headers | { [key: string]: string; } | undefined'.
    Type '{ cookie: string; append(name: string, value: string): void; delete(name: string): void; get(name: string): string | null; has(name: string): boolean; set(name: string, value: string): void; forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; }' is not assignable to type 'undefined'.ts(2322)

At the end it says it is not assignable to type 'undefined'. I thought if a value for a type is guaranteed to be one of it's union types, it shouldn't complain.

1
  • It seems like the methods are tripping typescript up. Commented Jan 4, 2021 at 16:13

1 Answer 1

1

node-fetch defines its own types that are incompatible with the DefinitelyTyped type definitions (node-fetch's are presumably more up-to-date). You should generally use a library's own types instead of DefinitelyTyped if both are available.

https://github.com/node-fetch/node-fetch/blob/master/@types/index.d.ts#L60 https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node-fetch/index.d.ts#L48

The library's type has RequestInit's body property as BodyInit | null, so the ability to sign it as null makes it incompatible with the other typing. Use the library's typing simply by importing it:

import fetch, { RequestInit } from 'node-fetch';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.