Importing an anonymous ES5 function using Typescript

I am currently facing an issue with ES6 import syntax when importing a third-party ES5 module that only exports a single unnamed function:

module.exports = function (phrase, inject, callback) { ... }

Since there is no default export and just an anonymous function output, my import and usage look like this:

import * as sentiment from 'sentiment';
const analysis = sentiment(content);

This results in a Typescript error:

error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof "sentiment"' has no compatible call signatures.

It appears that the error stems from incorrectly typing the ES5 import (no public typings file available). Initially, I had created the following definition assuming it was a default export:

interface IResults {
  Score: number;
  Comparitive: number;
}

declare var fn: (contents: string, overRide?: IDictionary<number>) => IResults;

declare module "sentiment" {
  export default fn;
};

However, since the import is not a default export, I am unsure of how to properly define the module and function. I attempted the following:

declare module "sentiment" {
  export function (contents: string, overRide?: IDictionary<number>): IResults;
};

Although this seems to be a valid export definition, it does not align with the anonymous call definition and triggers the following error:

error TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'typeof "sentiment"' has no compatible call signatures.

Answer №1

In this particular scenario, importing in the manner you are attempting will not work.
According to information provided under Modules: export = and import = require():

When using export = to import a module, you must utilize the TypeScript-specific import let = require("module") syntax for proper importation of said module.

Therefore, your approach should be as follows:

import sentiment = require("sentiment");
const analysis = sentiment(content);

The structure of the definition file needs to resemble the following:

declare function fn(contents: string, overRide?: IDictionary<number>): IResults;
export = fn;

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

Passing both the object and its attributes simultaneously for reflect-metadata in TypeScript is a feature that closely resembles functionality found

Instead of using DataAnnotation in C# to add meta attributes on properties, I am seeking a similar functionality in TypeScript for a ldap model class. The goal is to have decorators that can set the LDAP attribute used in the LDAP directory internally. ex ...

Updating the FormControl value using the ControlValueAccessor

I have developed a directive specifically for case manipulation. The code I created successfully updates the visual value using _Renderer2, but I am facing an issue with formGroup.value. Even though the directive visually changes the value as expected, t ...

Arranging an array of objects in Angular 7 according to the order of another array of objects

Yes, I know this question has been asked a million times before. However, I haven't found any helpful answers in those previous questions. Here's my dilemma: I have two arrays containing two different objects, each with a unique string property ...

rxjs iterates through an array executing each item in sequential order

Is there a way to make observables wait until the previous one has completed when they are created from an array? Any help is appreciated! export class AppComponent{ arr: number[] = [5, 4, 1, 2, 3]; fetchWithObs() { from(this.arr) ...

Typescript: Removing signatures with a filter

I am encountering a TypeScript error stating that .filter has no signatures. I'm unsure of how to resolve this issue. interface IDevice { deviceId: string; deviceName?: string; } const joinRoom = ({ userId, deviceId, deviceName }: IRoomParams ...

Ways to fetch data based on a specific relationship criterion

In my data structure, there is a Product entity and an Image entity with a OneToMany relationship. This means that One Product can have many Images attached to it. When an image needs to be removed, instead of deleting the data from the table, I have chos ...

The attribute 'X' is not found in the type 'HTMLAttributes<HTMLDivElement>'.ts(2322)

Encountered an issue using JSX sample code in TSX, resulting in the following error: (property) use:sortable: true Type '{ children: any; "use:sortable": true; class: string; classList: { "opacity-25": boolean; "transition-tr ...

Error encountered in TypeScript exclusively when implementing GetStaticProps function within a Next.js component and using the getStaticProps method

I'm encountering a challenge with TypeScript as I try to implement the type GetStaticProps in my code. Surprisingly, everything runs smoothly without any issues when this type is not used. The error message reported by TypeScript has left me puzzled. ...

Angular's mechanism for detecting changes in a callback function for updates

I have come across a puzzling scenario regarding a basic issue. The situation involves a simple component with a boolean property that is displayed in the template of the component. When I update this property within a callback function, the property is up ...

Understanding the significance of emitDecoratorMetadata in transpiled code

I have a question regarding the significance of the emitDecoratorMetadata option when transpiling TypeScript to JavaScript in an Angular 2 environment. If this option is set to false, and metadata is not included in the final code, what impact will it ha ...

What is the best way to update this payload object?

Currently, I'm developing a route and aiming to establish a generic normalizer that can be utilized before storing user data in the database. This is the function for normalization: import { INormalizer, IPayloadIndexer } from "../../interfaces/ ...

How can you display the value of a date type in a TextField?

I'm currently utilizing the TextField component from material-ui. My goal is to display the current date in the TextField and allow users to select another date. Is this feasible? When using type="date", the value set as {date} does not show up in th ...

Can you merge two TypeScript objects with identical keys but different values?

These TypeScript objects have identical keys but different properties. My goal is to merge the properties from one object onto the other. interface Stat<T, V> { name: string; description: string; formatValue: (params: { value: V; item: T }) =&g ...

Is it possible to deduce Typescript argument types for a specific implementation that has multiple overloaded signatures?

My call method has two signatures and a single implementation: call<T extends CallChannel, TArgs extends CallParameters[T]>(channel: T, ...args: TArgs): ReturnType<CallListener<T>>; call<T extends SharedChannel, TArgs extends SharedPar ...

Vee-Validate: Are flags on the field value yielding undefined results? Explained with TypeScript

The documentation states that by using a flag on the value of a field, I should be able to obtain a boolean. For example: computed: { isFormDirty() { return Object.keys(this.fields).some(key => this.fields[key].dirty); } }, I am working ...

Setting the desired configuration for launching an Aurelia application

After creating a new Aurelia Typescript application using the au new command from the Aurelia CLI, I noticed that there is a config directory at the root of the project. Inside this directory, there are two files: environment.json and environment.productio ...

Utilizing Modules and Classes in Typescript alongside Requirejs: A Comprehensive Guide

I've decided to implement RequireJs within MS CRM, but I'm unsure of how to integrate it with my TypeScript files. Each form in CRM currently has its own TypeScript file structured similar to this: // File Path .\_Contoso\scripts&bsol ...

Using absolute paths for templateUrl and styleUrls in Angular 6: A comprehensive guide

My angular application is filled with various components, but a recent requirement change forced me to switch from using relative URLs to absolute ones. Everything was going smoothly until I reached the templateUrl and styleUrls in the components. Despite ...

Transitioning from Global Namespace in JavaScript to TypeScript: A seamless migration journey

I currently have a collection of files like: library0.js library1.js ... libraryn.js Each file contributes to the creation of a global object known as "MY_GLOBAL" similarly to this example: library0.js // Ensure the MY_GLOBAL namespace is available if ...

Retrieving the key from an object using an indexed signature in Typescript

I have a TypeScript module where I am importing a specific type and function: type Attributes = { [key: string]: number; }; function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any { // ... } Unfortunately, I am unab ...