Importing a class from a JavaScript file in Typescript: a step-by-step guide

I need help with the following:

  • Importing a js file that defines a class: ./myClass/index.js
  • Declaring the public methods of MyClass (unsure of where to do this, whether in index.ts or another declaration file)
  • Creating a typescript file that exposes the class: index.ts

Here is an example of what I'm trying to achieve:

// index.ts
import MyClass from './myClass' // or require, or any other method that works
export {MyClass}

and

// myClass/index.js
export default class MyClass {
  ...
}

Unfortunately, this setup is not working as the import of ./myClass/index is unable to find the module.

I have attempted to create a ./myClass/index.d.ts file following an example from this resource, but I continue to encounter an Error: Cannot find module './myClass/index.js' at runtime :(

It seems like I may be missing some basic concepts in typescript, and I'm looking for clear resources to help me understand better.

Any suggestions or ideas?

Answer №1

When working with JavaScript, there is no such thing as export default class. Instead, you can structure your JS file as follows: myClass/index.js

"use strict";
class MyClass {
  hello(name) {
    console.log(`Hello ${name}`);
  }

}
exports.default = MyClass;

To provide Type definitions, create a file named myClass/index.d.ts

export default class MyClass {
  hello(name: string): void;
}

Next, you can import it into your TypeScript code like this.

/// <reference path="./myClass/index.d.ts" />
import MyClass from "./myClass";

const myInstance = new MyClass();
myInstance.hello("World");

Answer №2

When wrapping up your JavaScript file, make sure to include the following:

exports.MyClass = MyClass;

For TypeScript files:

import * as  IzendaSynergy  from './izenda/izenda_ui.js';

or

import { IzendaSynergy } from './izenda/izenda_ui.js';

In your tsconfig.json file:

  "allowJs": true

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

Display JSON values in sequence using Material-UI animations

I have received an array of JSON data from the API that looks like this: "fruits": [ { "id": "1", "fruit": "APPLE", }, { "id": "2", "fruit": ...

Pattern matching: Identify text elements specifically within an HTML tag

I've been experimenting with a text highlighting script. Check out my initial attempt here. Here's the code snippet: http://jsfiddle.net/TPg9p/3/ However, I encountered a problem – it only works with simple strings and not those containing HT ...

Sails.js encounters issues initializing Passport.js when SSL is implemented

Currently utilizing Sails.js (v0.9.4) and passport(local strategy) with no issues. The need arises to configure Sails.js behind SSL. Therefore, the setup includes: (Port 8080 selected for SSL). Upon starting Sails, it responds correctly, except for those ...

Is there a way to check if a user has previously visited a URL and automatically redirect them back to that page if they have

I'm looking for a way to detect if a user has already opened a specific link or URL in their browser tab. Is it possible to redirect the link to an active tab if the URL is already open? For example, if a user clicks on a link and JS code opens a new ...

How do I utilize ng-repeat in Angular to pass a variable that specifies the number of repetitions?

When working on my app, I encountered a situation where I needed to retrieve elements from a database and display them using ng-reat. Everything was going smoothly until I realized that within this list, there was another set of data that required a separa ...

Comparing Buffer and Uint8Array in Node.js

Exploring the documentation for the fs module 1, we come across the following regarding the writeFile method: const data = new Uint8Array(Buffer.from('Hello Node.js')); Further in the documentation 2, it states: With TypedArray now available, ...

Struggling to dynamically access element IDs with JavaScript

As I loop through my list of students and add them to my page, I encounter an issue where each student's unique ID is not being passed correctly. When the getStudentInfo function is called, it always returns the ID of student1, regardless of which stu ...

Retrieve selected value from HTML input with datalist and use it as an argument in a method

I have a datalist in my HTML input where I need to pass the selected value into JavaScript / Angular. It must be passed because the datalist is being used in an HTML table with multiple entries. Most examples I've come across show how to grab the valu ...

Access the contents of MUI Modal (Dialog) even when it's closed

I'm currently working on an app using Material-ui and firebase authentication. My goal is to integrate firebaseui's authentication within a MUI Dialog component. The issue I've encountered is that in order for the authentication component t ...

When the class name is identical, the click event appears to be malfunctioning

Why isn't the click event working in this code? What am I doing wrong? $(document).ready(function() { $('.dashboardList').click(function() { alert("hello"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1. ...

What exactly happens behind the scenes when JSON.stringify() is called?

How does the replacer argument function extract keys and values from an object's value and map them to its key and value arguments in the JSON.stringify(value, replacer, space) method? I have grasped that the key of the object becomes the key paramet ...

Changing the location of an ArcGIS map with a click event in a Vue application

I am attempting to dynamically update a map to display my current location using Vue. I have created an onClick event that updates the props and sends them to my map component. To trigger a re-render of the map component when the data changes, I am utilizi ...

Is it possible to implement formvalidation.io in a React project that is using Materialize-css?

Can the formvalidation.io plugin be used with React and Materialize-css in a project? My project consists of multiple input components that may or may not be within a form. I want to utilize formvalidation for input validation. However, I am unable to find ...

Tips for displaying an alert after a successful form submission and ensuring user input validation

I created a form with PHP code to send emails, but I'm struggling to add an alert without page refresh upon submission. The alert needs to display in green or red text below the button. Validation for email input is needed, as well as protection again ...

Error: Access Denied - discord.js bot command cannot be executed due to lack of authorization

Every time I initiate the bot and try to execute my "ping" command, an error occurs: js:350 throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: Missing Access at RequestHandler.execute (C: ...

Can the combobox be used for organizing items?

Can someone help me simplify this code? When 'info' is selected from the combobox, the corresponding articles should be displayed, and the same goes for 'Berita'. Here's the lengthy script I have, using the post method. Any suggest ...

Recommendations for organizing code with respect to models in Angular using TypeScript

Within my C# backend, I structure my entities and entity lists using classes. Any needed functions or methods are simply added to the corresponding class. On the contrary, in Angular/TypeScript examples, models are typically defined as interfaces. This ra ...

Error: The function sendFile does not exist in the method res.status(...)

As a newcomer to this field, I must apologize if my issue has an obvious solution. However, I am encountering the following error: TypeError: res.status(...).sendFile is not a function at app.get (/root/discordtest/server.js:10:19) at callbacks (/ ...

Tips for concurrently and asynchronously executing multiple AJAX requests

I am working with a javascript object named Agendamento which includes the following key parts: const Agendamento = { // ... storeResultados: async function (consulta) { //... $.ajax({ type: 'POST', ...

Ways to retrieve the innerHTML content in Mozilla Firefox

Look at this HTML code snippet: <div id="divTest"> Hello <input type="text" id="txtID" value="" /> <input type="button" onclick="getForm();" value="Click" /> </div> Also, check out this JavaScript function for retrievi ...