'How to extend a .js file with a .ts file

Let's say I have a legacy codebase with a .js file that looks like this:

// myFile.js
export const returnStuff = () => 'stuff';

Now I want to add functionality to this file, but this time I want to use TypeScript. I don't want to rewrite the legacy .js file, I only want to "extend" it with new functionality written in TypeScript:

// myFile.ts
export const returnSomethingElse = (suffix: string): string => 'something else' + suffix;

I want myFile.ts to contain all the exports from myFile.js, and also this new export that is added.

Is this possible? If I try to do this I get the following error in files that require returnStuff:

TS2305: Module '"path/to/myFile"' has no exported member 'returnStuff'

I've looked at ambient contexts in TypeScript, but that doesn't seem to solve the problem since now I have to declare the types for myFile.js. I want to avoid this, since at that point I might as well rewrite myFile.js to TypeScript.



Solution 1:[1]

It sounds like you want to create a new separate file that exports everything myFile.js and also some further exports defined in the file itself.

I suspect if the base filenames are the same, you'll struggle, but you can readily do this with a slightly different base name. For instance, you might rename myFile.js to myOldFile.js then write myFile.ts like this:

export * from "./myOldFile.js";

export const returnSomethingElse = (suffix: string): string => 'something else' + suffix;

export * re-exports all of the named exports of a module. So anything that used to import returnStuff from "myFile" will continue to do so, it's just a re-export now instead of the original (which is harmless and doesn't introduce overhead).

Alternatively, since TypeScript is (mostly) a superset of JavaScript, you might just change myFile.js to myFile.ts and add your new things to it. You may get lots of warnings about "implicit any" and such (and sadly, there's no @ts-ignore for multiple lines yet), but...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 T.J. Crowder