Home > OS >  How do I provide an implementation of fetch Headers in TypeScript
How do I provide an implementation of fetch Headers in TypeScript

Time:02-25

Specifically, I am using a 3rd party library which has the following property on an interface:

readonly Headers: typeof Headers;

Where of course headers is:

var Headers: {
new (init?: HeadersInit | undefined): Headers;
prototype: Headers; }

I am struggling to understand what this is trying to tell me. As far as I can tell the interface is expecting an instance of Headers but it complains:

Property 'prototype' is missing in type 'Headers' but required in type '{ new (init?: HeadersInit | undefined): Headers; prototype: Headers; }'.ts(2741)

Is this trying to tell me that instead of passing an object it is expecting a type which it can later instantiate? If so then how do I create a type to handle this?

What I am trying to do is so simple, just want to be able to supply a Header with Authorization but I do not get what it expects!

Any sample would be much appreciated :)

CodePudding user response:

Based on what you've provided, you need to supply the Headers constructor:

{ Headers: Headers }

rather than an instance:

{ Headers: new Headers() }

The JSDoc comment clarifies this:

    /**
     * The `Headers` object constructor.
     */
    readonly Headers: typeof Headers;

and the README also clarifies this:

Note: All functions and classes using the REST API allow a serverSettings parameter to configure requests. Requests are made using the fetch API, which is available in modern browsers or via npm install fetch for node users. The whatwg-fetch npm package can be used to polyfill browsers that do not support the fetch API.


Although you left out what seems to be your real question, I think you want to know how to use this package: install node-fetch first, then use the ServerConnection.makeSettings() method, which will generate the (default) settings you need, and create your request init using the Headers class from node-fetch:

TS Playground

import {Headers} from 'node-fetch';
import {ServerConnection} from '@jupyterlab/services';

const settings = ServerConnection.makeSettings();

ServerConnection.makeRequest(
  'https://url.example',
  {
    headers: new Headers([
      ['your_headers', 'go_here'],
    ]),
  },
  settings,
);
  • Related