Is there a way to prevent the TS2306 error when an ES6 TS module imports a module similar to AMD?

I'm working with file A.js (non-TypeScript) which has the following structure:

module({
}, function (imports) {
    return {
        foo: function () {
            // ...
        }
    };
});

This file follows a module format similar to AMD, with an implementation resembling requirejs but in a slightly different format.

Now, file B.ts (TypeScript) is trying to import it:

import A from '../old-code/A'
console.log(A)

However, attempting this import results in an error:

ERROR in ./src/app.ts
(9,17): error TS2306: File '/path/to/B.js' is not a module.

Is there a solution to this issue? How can TypeScript properly import the non-TypeScript file?

As someone new to TypeScript, I wonder if creating a type definition for it could solve the problem?

EDIT: I came across information about declaration files, but it doesn't address importing non-TypeScript files.

I am hopeful that there is a way to define the imports and exports of the file. If not, it would be great to have this feature added in the future.

Answer №1

Similar to AMD, the module format is implemented in a way that closely resembles requirejs, with just a slightly different structure.

From what I understand, importing non-standard modules in TypeScript would require adjusting the compiler, which may not be feasible for regular users.

However, you can still find a workaround by using something like

declare function require(mod: string): any
in your module system. This allows you to import your module at runtime using require('A'), but there won't be type checking during compilation.


If you're not utilizing the allowJS flag, you can create a declaration file like this:

A.d.ts

declare var a: {
    test: number
}
export = a

It's important to follow the naming convention - if you have a file named A.js, a corresponding A.d.ts will be automatically searched by the compiler for import * as A from './A'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ins and outs of Angular's type checking mechanisms

I have a few different scenarios on my mind. Imagine if I make an http call to fetch all movies from my php backend api. This is observable, so I need to subscribe to it. // Here's my service getAll() : Observable<Movie[]>{ this.http.get ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...

Retrieving an individual instance of a component

Is there a way to access a specific instance of a component within an app that uses it multiple times in other components? Currently, when I use the query command "fixture.debugElement.query(By.directive(ComponentName)).componentInstance;", it only recogni ...

Exploring the Factory Design Pattern Together with Dependency Injection in Angular

I'm currently implementing the factory design pattern in Angular, but I feel like I might be missing something or perhaps there's a more efficient approach. My current setup involves a factory that returns a specific car class based on user input ...

Navigating to different HTML pages by utilizing <a> elements in Angular 2

As a newcomer to Angular 2, I've decided to build my personal website using this framework. The main page of my website contains bio information, while the other page will feature blog content. Both pages will have a shared header and footer, but diff ...

Retrieving properties of a universal function

I am facing a challenge in creating a class that accepts a factory function as one of its parameters in the constructor, which is then used to create instances of another class. The implementation below is written in JavaScript. // item to create class Ite ...

This error occurs because the argument type 'AsyncThunkAction<any, void, {}>' cannot be assigned to a parameter of type 'AnyAction'

I encountered an error that I couldn't find a solution for on Stack Overflow The argument of type 'AsyncThunkAction<any, void, {}>' is not compatible with the parameter of type 'AnyAction'. <MenuItem onClick={() =&g ...

Adding SVG to Component

I am attempting to embed an SVG element (retrieved using http.get()) into a 'icon' component. export class BgIcon { private svgSrc_: string; icon_: Icon; @Input('svg-src') set svgSrc(value: string) { this.svgSrc_ = value; ...

What's causing Angular to not display my CSS properly?

I am encountering an issue with the angular2-seed application. It seems unable to render my css when I place it in the index.html. index.html <!DOCTYPE html> <html lang="en"> <head> <base href="<%= APP_BASE %>"> < ...

Function modifies global variable

What could be causing the global variable to change when using the function write_ACK_ONLY()? I'm passing the array rxUartBuffer to write_ACK_ONLY() as data = new Array(20), but upon checking the Log Output, it seems that the function is also modifyin ...

Unlocking Not Exported Type Definitions in TypeScript

Take a look at this TypeScript code snippet: lib.ts interface Person { name: string; age: number; } export default class PersonFactory { getPerson(): Person { return { name: "Alice", age: 30, } } } ...

Issue with setting value using setState in TypeScript - what's the problem?

Every time I attempt to update the value of currentRole, it appears highlighted in red. Here is a screenshot for reference: const Container: React.FC<ContainerProps> = ({ children }) => { const [role, setRole] = useState<string>(); useE ...

Error: Attempting to modify the ip property of an #<IncomingMessage> object that is read-only

Currently, I am in the process of developing a middleware that is intended to assign the user's IP address based on the cloudflare header provided. This method has worked successfully on previous projects of mine, but now it seems to be encountering i ...

Steps for deactivating SSR on specific pages in Nuxt3

I'm currently working on a project using Nuxt 3. One part of the application can only be accessed when the user is logged in. I'm trying to figure out how to turn off SSR for these specific routes, but still keep it enabled for the public routes. ...

ngRepeat momentarily displays duplicate items in the list

There is a modal that appears when a button is clicked. Inside the modal, there is a list of items that is populated by data from a GET request response stored in the controller. The issue arises when the modal is opened multiple times, causing the list t ...

Tips on navigating to the next or previous variable reference in VS Code

While using TypeScript in VS Code, is there a similar shortcut like in Visual Studio for easily navigating between variable references within the open script? ...

Is there a way to extract the HTMLElement[] type from the DOM?

In my TypeScript project, I am trying to gather all the top-level elements of a page using the code snippet below: const getHTMLElement() : HTMLElement[] { const doc = document.body.children; const list : HTMLElement[] = []; for (let c of Array.f ...

Mastering the art of debugging feathersjs with typescript on VS Code

I am facing an issue while trying to debug a TypeScript project with FeathersJS using VSCode. Whenever I try to launch the program, I encounter the following error: "Cannot start the program '[project_path]/src/index.ts' as the corresponding J ...

What is the process for setting the value of a TextField based on a Dropdown Selection?

I have a question regarding the code snippet below. I am wondering how to set the value of a specific TextField based on the selected item in a Dropdown component named ChildComponent. import * as React from "react"; import ChildComponent from './Ope ...

How can I ensure that a user variable stored in an Angular6 service remains defined and accessible from other components?

Currently, I am working on an Angular app and facing a challenge. After receiving a user variable from an asynchronous call to Firestore Cloud, I noticed that the variable is successfully set (verified using console.log()). However, when I navigate between ...