Bringing in an interface that has been declared using export = alongside an ambient module

When working with a Typescript module, it is possible to import various exports including classes, interfaces, variables and enums that were exported using the old export = syntax.

However, I have noticed that when attempting this with an ambient module, the compiler (version 1.8.10) does not seem to recognize the import statement.

Declaration File:

//Module declaration
declare module "foo" {
    interface barProc {
        (): any;
    }

    //Note: if I use the function equivalent to the interface this works ok.    
    function worksOk(): any;

    export = barProc;
}

Main File:

//Module usage 
import myFunc = require("foo");
myFunc();

In this scenario, the compiler raises an error stating that myFunc is an unknown identifier and the import line doesn't show up in the output Javascript file.

Note: Although in the example illustrated, no other members are added to the interface for simplicity reasons, the interface is used because the JavaScript library being modeled has members on the function.

Is there anything wrong with how I'm doing this, or is there a workaround available?

Answer №1

barProc is defined as an interface, making it a type rather than a variable of that type. While you can export and utilize it as a type in other parts of your code, you cannot directly invoke it as a function like in the sample provided.

The sample given can be likened to:

interface barProc {
    (): any;
}

barProc();

When presented this way, it becomes evident that it is incorrect. A correct approach would be more along the lines of:

interface barProc {
    (): any;
}

var myFunc: barProc;

myFunc();

Transforming this into a module structure would result in:

declare module "foo" {
    interface barProc {
        (): any;
    }

    var myFunc: barProc;

    export = myFunc;
}


// Usage in another part of the code:

import myFunc = require("foo");
myFunc();

By following this pattern, you should achieve the desired outcome.

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

Typescript allows for the creation of a static class that can be accessed without needing to instantiate it

My goal is to design a TypeScript class that can be accessed directly without the need to create new instances. This is necessary because some classes will modify the variables in this shared class, while others must reference those changes. Below is the ...

Guide to correctly importing a class definition from a module in TypeScript

Having trouble integrating the AsyncAPI Generator into my typescript project. The generator, being a commonjs module, is causing some complications. import { Generator } from '@asyncapi/generator'; const generator = new Generator('@asyncapi ...

Altering a public variable of a component from a sibling component

Within my application, I have two sibling components that are being set from the app.component: <my-a></my-a> <my-b></my-b> The visibility of <my-a> is determined by a public variable in its component: @Component({ module ...

What limitations do we face when trying to change the objects received by a component through @input() in Angular?

Recently, I made the leap from angular 7 to angular 11 in my app. Everything was running smoothly until I decided to incorporate angular universal for server-side rendering. Shortly after implementing server-side rendering, a flurry of errors cropped up, ...

Having difficulty incorporating TypeScript into Vue

A little while ago, I set up a vue project using vue init webpack . and everything was running smoothly. Recently, I decided to incorporate typescript and ts-loader. I created a file in the src directory with the following content: declare module '* ...

Error in React TypeScript: The onCreate function is causing an overload error. Specifically, overload 1 of 2, with 'props: Readonly<{}>', is creating issues

Why does it work in Javascript but show an error in TypeScript? How can I fix this? App.tsx class App extends React.Component<{}, null> { handleCreate = (data) => { console.log(data); } render() { return ( ...

What changes do I need to make to this function in order to properly wait for the results?

I seem to have identified the issue in my code. export async function hourlyUpdate(bot:Discord.Client){ let result=new Promise<ActiveSubscriberList>(async (resolve,reject)=>{ let fileData=await getDataFromFile() let resultList ...

Unable to utilize Google Storage within a TypeScript environment

I'm encountering an issue while attempting to integrate the Google Storage node.js module into my Firebase Cloud functions using TypeScript. //myfile.ts import { Storage } from '@google-cloud/storage'; const storageInstance = new Storage({ ...

What imports are needed for utilizing Rx.Observable in Angular 6?

My goal is to incorporate the following code snippet: var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: { lat: -25.363, lng: 131.044 } }); var source = Rx.Observable.fromEventPattern( function (han ...

How to set the default option in a select dropdown using Angular and Types

It's been a while since I last worked with Angular and now I'm tasked with working on an existing system. I introduced an NgModal dialog to send text messages, designed as shown here: https://i.sstatic.net/67U1M.png Below is the code snippet I ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

Using Snap SVG in a React application with Next.js and TypeScript

Query I have been attempting to incorporate SnapSVG into my React project, but I am encountering difficulties getting it to function properly from the outset. Can someone provide assistance with the correct configurations? I do not have much experience wi ...

Utilizing Ramda lenses for composition in Typescript with the useState set function in React

I am currently learning functional programming and exploring event handling in React. Let's consider the following example: interface Todo { task: string done: boolean } interface TodoProps { todo: Todo onChange: ChangeEventHandler< ...

Is it possible to combine two enums in TypeScript to create a single object with key-value pairs?

Incorporating two enums named Key and Label, as well as an interface called IOption, the goal is to generate an array of objects known as IOptions. const enum Key { Flag = 'flag', Checkbox = 'checkbox', Star = 'star&apo ...

When utilizing useContext, the returned value may not always be what is anticipated, as it

Whenever I click the submit button in the consumer, instead of getting "useModal", I'm receiving "default block". Despite following all tutorials and guides online, I can't seem to get the expected value no matter what I do. This is a component ...

Create a series of actions that do not depend on using only one occurrence of the WriteBatch class

My goal is to create a series of batch actions using functions that do not require a specific instance of WriteBatch. Currently, I am passing an instance of the WriteBatch class to the functions so they can utilize the .set(), .update(), or .delete() metho ...

The reset() function in Angular does not set form controls to empty values

When following the Hero guide, I encountered an issue while trying to reset all fields in the model using the provided code snippet. this.form.reset({ "firstName": "", "lastName": "bzz", "reporter": "" }); The problem arises when only non-empty fi ...

How can the parent component in React be connected to access the history prop?

There is a method called showInfo that is accessed by two components, Child1 and Child2. Originally, the showInfo method was located within the Child1 component as shown below: const Child1 = ({history}: RouteComponentProps) => { type Item = { ...

What is the optimal method for defining a JSON serialization format for a TypeScript class?

Currently, I am in the process of developing a program using Angular and TypeScript. Within this program, there is a specific class named Signal that consists of various properties: export class Signal { id: number; obraId: number; obra: string ...