Exploring the Integration of OverlayScrollbars with TypeScript

Currently, I am delving into TypeScript utilizing a project built on ASP.NET Core 3.0 and the VS 2019 IDE. Recently, I acquired the OverlayScrollbars plugin via npm: .

npm install overlayscrollbars
npm install @types/overlayscrollbar

Provided below is a straightforward usage example:

/// <reference path="../../libs/npm/@types/overlayscrollbars/index.d.ts" />

import OverlayScrollbars from "../../libs/npm/@types/overlayscrollbars/index"; // ../../libs/npm/overlayscrollbars/js/overlayscrollbars.js

$(() => {
    OverlayScrollbars($("body")[0], { });
    //$("body").overlayScrollbars({ });
});

The solution compiles successfully, the files are transpiled (the target is switched as per the comment - this will be an area of future inquiry for me) and then copied to the wwwroot. At this stage, the files are referenced correctly.

Here is my tsconfig.json configuration file:

{
  "compileOnSave": true,
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "noEmitOnError": true,
    "noImplicitAny": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "target": "es6",
    "typeRoots": [ "node_modules/@types/**" ]
  },
  "exclude": [
    "node_modules",
    "**/*.spec.ts"
  ]
}

Despite this success, upon executing

OverlayScrollbars($("body")[0], { });
, I am met with
Uncaught SyntaxError: The requested module does not provide an export named 'default'
at runtime.

https://i.stack.imgur.com/4jj6U.png

Alternatively, using the second method (

$("body").overlayScrollbars({ });
), I encounter compilation error
TS2345: (TS) Argument of type '{}' is not assignable to parameter of type string
along with some peculiar intellisense issues:

https://i.stack.imgur.com/zFjW5.png

https://i.stack.imgur.com/iCuPe.png

Addressing this problem in C# would be more straightforward, but due to my limited knowledge of TS, solving it seems challenging without resorting to trial and error.

Attached is a basic project that demonstrates this issue:

Any assistance or guidance provided would be greatly appreciated.

// EDIT 1

@Kewin Dousse

I want to clarify that I specifically reference the declarations because I import the actual files in my .cshtml file.

<link href="~/libs/npm/overlayscrollbars/css/OverlayScrollbars.css" rel="stylesheet" />
...
<script src="~/libs/npm/overlayscrollbars/js/jquery.overlayScrollbars.js"></script>

This approach was chosen to preemptively address the aforementioned issues, whether opting for the JQuery or Vanilla version of OVerlayScrollbars.

My understanding is that when using imports, the browser must directly point to the JavaScript file with the explicit .js extension for functionality.

To resolve this, I have set up gulp to substitute the path to the d.ts file with the one in the comment.

If I include this line:

import OverlayScrollbars from "../../libs/npm/@types/overlayscrollbars/index"; // ../../libs/npm/overlayScrollbars/js/jquery.overlayScrollbars.js

An editor warning pops up in my .ts file:

https://i.stack.imgur.com/pU2wS.png

And there's a runtime error:

https://i.stack.imgur.com/Mvucg.png

When employing this code:

import { OverlayScrollbars } from "../../libs/npm/@types/overlayscrollbars/index"; // ../../libs/npm/overlayScrollbars/js/jquery.overlayScrollbars.js

I encounter compilation error TS2305 displaying an unusual path:

https://i.stack.imgur.com/mwE3R.png

Using this line:

import * as OverlayScrollbars from "../../libs/npm/@types/overlayscrollbars/index"; // ../../libs/npm/overlayScrollbars/js/jquery.overlayScrollbars.js

Errors out with TS2349:

https://i.stack.imgur.com/AInLQ.png

Accompanied by an intellisense error:

https://i.stack.imgur.com/56eza.png

(For potential VS fix, consider changing the path to

import OverlayScrollbars from "../../libs/npm/@types/overlayscrollbars/index";
)

The only method that currently works for me is hand-crafting the declaration for the JQuery extension like so:

interface JQuery {
    overlayScrollbars(
        options: OverlayScrollbars.Options,
        extensions?: OverlayScrollbars.Extensions
    ): JQuery;
    overlayScrollbars(
        filter?: string | ((element: Element, instance: OverlayScrollbars) => boolean)
    ): OverlayScrollbars | OverlayScrollbars[] | undefined;
}

Utilizing it as follows:

$("body").overlayScrollbars({ });

While removing the module import altogether.

I acknowledge that this custom declaration aligns with what the declarations file is intended to accomplish, yet, inspecting its content, the setup fails to function properly.

Answer №1

The issue at hand is that you are not correctly importing the code for OverlayScrollbars into your file; instead, you are only importing its type definitions.

When referring to type definitions like

"../../libs/npm/@types/overlayscrollbars/index"
, it points to the @types/overlayscrollbars npm package, which solely consists of declaration files. Declaration files add TypeScript types to JavaScript libraries for efficient usage with TypeScript, meaning they only specify types and do not execute any JavaScript code.

You have imported the declaration file for the overlayscrollbars package, allowing TypeScript to understand the types used by that JS library. However, you still need to import the actual library code itself.

To import the library, follow a similar approach as if you were working with JS. While I'm unsure of the specific exports of this library, your import statement may resemble the following:

import OverlayScrollbars from "../../libs/npm/overlayscrollbars";

If the above doesn't work, you can also try these alternatives:

import { OverlayScrollbars } from "../../libs/npm/overlayscrollbars";
import * as OverlayScrollbars from "../../libs/npm/overlayscrollbars";

The way in which the module exports its symbols might vary, necessitating different import methods (which would require inspecting the lib's export structure).

The second error message indicates that you are invoking overlayscrollbars incorrectly, with the first argument expected to be a string.

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

Extracting PDF files using API within Angular services

I have set up a Java-based API on a server, with the URL being "ex.com". This API has an endpoint that returns a PDF file, with the URL set as "ex.com/pdf". For this endpoint, a POST request is required with a parameter specifying the requested PDF, like ...

Syntax for TypeScript generic promises definition

I'm struggling to fully grasp the definition of Promise in TypeScript, as shown below: /** * Represents the completion of an asynchronous operation */ interface Promise<T> { /** * Attaches callbacks for the resolution and/or rejectio ...

How to correctly type socket events when developing a customized useSocket hook in TypeScript?

Both my socket server and socket client are set to listen for a specific range of events. Below are the definitions for these socket events: import { Server } from "socket.io"; import { Socket } from "socket.io-client"; import { Disconn ...

Set every attribute inside a Typescript interface as non-mandatory

I have defined an interface within my software: interface Asset { id: string; internal_id: string; usage: number; } This interface is a component of another interface named Post: interface Post { asset: Asset; } In addition, there is an interfa ...

Extremely sluggish change identification in combination Angular application

We are encountering consistent issues with slow change detection in our hybrid AngularJS / Angular 8 app, especially when dealing with components from different versions of the framework. The problem seems to arise when using older AngularJS components wit ...

Setting up tsconfig.json to enable support for either string literals or string templates involves adjusting the compiler options

After utilizing swagger codgen with the typescript-aurelia template to create API code, I noticed that a significant amount of string literals were being used in the resulting code. Despite encountering errors when running the transpiler tsc from the comma ...

I am encountering an issue where Typescript paths specified in the tsConfig.app.json file are not resolving properly

I have defined path settings in my tsconfig.app.json file like this: "paths": { "@app/core": ["./src/app/core"] } Every time I run a test that includes import statements with relative paths, it throws the following error: ...

What is the significance of having nodejs installed in order to run typescript?

What is the reason behind needing Node.js installed before installing TypeScript if we transpile typescript into JavaScript using tsc and run our code in the browser, not locally? ...

Ways to check the functionality of the secondary tier in the api.send method

Currently, I am testing a function that involves returning a promise and subsequently calling the same function again at a second level. However, I am facing difficulties in accessing this second level of call. Below is the function code: itemToForm = () ...

Tips for setting values to the child component property in Angular 4

When I was using ngif, I encountered an issue with getting the element reference of the child component. After extensive searching, I discovered that in order to access the element, I needed to use view children instead of view child. While I am able to ge ...

Utilizing React Router with the power of useCallback

My route configuration is set up as follows: const defineRoutes = (): React.ReactElement => ( <Switch> <Redirect exact from="/" to="/estimates" /> <Route exact path="/estimates" component={CostingPa ...

What is the best way to remove query string parameters prior to running a function when a button is clicked?

I'm facing an issue trying to implement a button that filters events based on their tags. The problem arises when the tag value in the query string parameter does not clear when other buttons are clicked. Instead, the new filter tag value adds up with ...

Utilizing Higher Order Components with TypeScript in React Applications

My React component is typed with a generic, and I've extended it with a higher order component (redux-form). Below is a simplified version of my class and the HOC being applied: import * as React from "react"; interface MyFormProps<D> { pr ...

What is the best way to incorporate dynamic infographics into an ionic app?

Looking to design unique infographics for my ionic app, similar to the ones seen here: Any recommendations on tools or strategies for creating these infographics? ...

TypeORM does not have the capability to effectively remove a row when there is a ManyToOne or

I'm currently grappling with a problem that has me stumped. I've spent countless hours trying to find a solution, but to no avail. I'm using MS-SQL on Azure. The structure of my entities is as follows: Customer and Visits: OneToMany (Prima ...

Exploring nested static properties within TypeScript class structures

Check out this piece of code: class Hey { static a: string static b: string static c: string static setABC(a: string, b: string, c: string) { this.a = a this.b = b this.c = c return this } } class A { static prop1: Hey static ...

Implementing Facebook Javascript SDK to enable login and trigger re-authentication using React Web and Typescript within a component

As a newcomer to stack overflow, I welcome any suggestions on how I can improve my question. I'm in need of guidance concerning logging a user into facebook and requiring them to authenticate their profile or select another profile manually, rather t ...

Iterate over the key-value pairs in a loop

How can I iterate through a key-value pair array? This is how I declare mine: products!: {[key: string] : ProductDTO}[]; Here's my loop: for (let product of this.products) { category.products.push((product as ProductDTO).serialize()); } However, ...

When I attempt to add a todo item by clicking, the Url value is displayed as "undefined"

I am facing an issue with my household app where, upon clicking the button to navigate to the addtodo page, the URL specific to the user's house is getting lost. This results in the todolist being stored as undefined on Firebase instead of under the c ...

When utilizing the package, an error occurs stating that Chart__default.default is not a constructor in chart.js

I have been working on a project that involves creating a package with a react chart component using chart.js. Everything runs smoothly when I debug the package in storybook. However, I encountered an error when bundling the package with rollup, referenc ...