Merge JavaScript code with its TypeScript definition from different files

Viewed 178

I want to use a specific file from a repository without installing its NPM package, but it was coded in JavaScript and has a separate definition file.

I want to merge the JavaScript implementation with the type definition, so I ended with this approach:

import { default as HeadersImplementation } from '../node-fetch/src/headers.js';
import { Headers as HeadersDefinition, HeadersInit } from '../node-fetch/@types/index';

const Headers: {
  prototype: HeadersImplementation;
  new(init?: HeadersInit): HeadersDefinition;
} = HeadersImplementation;

const teste = new Headers();
teste.append('Hello', 'World!');

Is there an easy way to merge the class implementation with its definition?

2 Answers

I would re-export it so that using it is clean and straightforward in other modules:

Don't forget to re-export the HeadersInit type so that you can strongly type a constructor input argument

./src/headers.ts:

// @ts-ignore
import {default as HeadersImplementation} from '../node-fetch/src/headers.js';
import {type Headers} from '../node-fetch/@types/index';
export {type HeadersInit} from '../node-fetch/@types/index';

const H: typeof Headers = HeadersImplementation;
export {H as Headers};

./src/index.ts:

import {Headers, type HeadersInit} from './headers.js';

const init: HeadersInit = [['name', 'value']];
const test = new Headers(init);
test.append('Hello', 'World!');
console.log([...test]);

$ tsc && node dist/index.js
[ [ 'hello', 'World!' ], [ 'name', 'value' ] ]

you don't need to touch any part of that code, nor try to merge things in your own code. just have the two files with the same name and import in your code what you need.

you need just 2 installs in your project, which are possibly already in your project.

steps to follow:

  • download/copy js file into a folder in your project
  • download/copy .d.ts file into the same folder and rename it so both have the same names; i.g. headers.js and headers.d.ts
  • install typescript if you haven't done so: npm i -D typescript (you possibly have already done so)
  • install typings module: npm install --save @types/node
  • go ahead and import whatever you want: import {Headers} from "./headers.js"
  • enjoy the types in your own code

you can also:

  • copy all the files in the src folder into a folder of your choice; node-fetch will serve better
  • copy index.d.ts into this folder. voila! you will get types for node-fetch for everything defined in it.
  • this time import from the folder: import {Headers} from "./node-fetch"
Related