Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following:

interface MyInterface{
// ...
}


class MyClass{
 public myMethod(): MyInterface { /* code */ }
}

export = new MyClass();

A JavaScript project can easily install and import the library like this:

const myLib=require('my-lib');

myLib.myMethod(); // Works fine

Similarly, a TypeScript project can also import the library successfully:

import * as myLib from 'my-class';

myLib.myMethod(); // Works as expected

However, I also want to export MyInterface for TypeScript projects so that they can use it like this when importing my library:

import {MyInterface} from 'my-lib';

function anotherFunction(arg: MyInterface){

}

I am unsure about how to properly export components in my main.ts file in order to achieve this functionality while still supporting JavaScript-based projects.

Answer №1

To utilize both the interface and class, follow these steps:

// my-library

export interface MyInterface{
// ...
}


export class MyClassStatic{
 // If your method does not require any context (this), declare it as 'static'
 public static myMethod(): MyInterface { /* code */ }
}

export class MyClass{
     public myMethod(): MyInterface { /* code */ }
}

When coding,

import * as myLibrary from 'my-library';

// Accessing a static method
myLibrary.MyClassStatic.myMethod();

// Accessing class members 
const myInstance = new myLibrary.MyClass();
myInstance.myMethod();

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

Formik's handleSubmit function appears to be malfunctioning

I have encountered a puzzling issue with Formik implementation in my two components. Despite implementing Formik in the same way for both components, I am facing a problem where `handleSubmit` works in one component but not in the other. You can check out ...

Containers shared among Next.js pages within a folder

Is it possible to have a shared container for all pages within a specific folder in NextJS? One potential solution could involve the following code: // pages/folder/index.js export default function Container({ children }) { return <Container>{ch ...

Is there a way to pass a form error to the parent component as a parameter in React?

I am just starting to learn React. I have created a form and I want to inform the parent component about any input errors that occur. I attempted to use the variable myError as a prop similar to how I used the next method, but unfortunately, it did not wor ...

How is it that this JavaScript task does not trigger an error: const a = (1, 2, 3, 4);

let x = (5, 6, 7, 8); console.log(x); let y = 5, 6, 7, 8; console.log(y); In the example above, x will be assigned a value of 8, while the second line will result in an error. What is the reason behind the success of the first assignment? How does it qua ...

Is it possible to modify the location of my CSG object prior to performing subtraction in Threejs with ThreeCSG?

Looking to carve out specific "voids" in platforms using ThreeCSG. The goal is to have these voids positioned at particular locations on the larger platform. var geometry = new THREE.CubeGeometry( 500, 10, 500 ); var hole_geometry = new THREE.CubeGeom ...

What is the best way to target the iframe within the wysihtml5 editor?

Currently, I am utilizing the wysiwyg editor called wysihtml5 along with the bootstrap-wysihtml5 extension. As part of my project, I am designing a character counter functionality that will showcase a red border around the editor area once a specific maxl ...

Retrieve class attributes within callback function

I have integrated the plugin from https://github.com/blinkmobile/cordova-plugin-sketch into my Ionic 3 project. One remaining crucial task is to extract the result from the callback functions so that I can continue working with it. Below is a snippet of ...

Is there a way to modify the text of image URLs using JavaScript?

My method of replacing a specific word in text works like this: document.body.innerHTML = document.body.innerHTML.replace(/katt/g, "smurf"); However, when I try to replace an image URL in HTML using the same line of code, it doesn't seem to work. H ...

"Troubleshooting: Why are errors not appearing in ts-node

Whenever I encounter an error in my code while compiling with ts-node, the error does not seem to appear in the console. For instance:let data = await fs.readFileSync(path); In the following code snippet, I am using "fs" to read a file by passing a path ...

Converting JQueryPromise to Promise: A step-by-step guide

In my current project, there is a code snippet that produces a JQuery promise: const jqProm = server.downloadAsync(); I am interested in integrating this promise within an async function. I was thinking of creating something similar to the C# TaskComplet ...

Tips for implementing a delay in HTTP requests using RxJS 6.3.0

When I try to use delay with the HTTPClient object, it gives me the following error: Cannot invoke an expression whose type lacks a call signature. Type 'Number' has no compatible call signatures. TypeScript Concerns: import { delay } from & ...

merging inline scripts within the <head> section

I have the following code snippet in my HTML file and am looking for ways to optimize its loading process. <script type="text/javascript"> function downloadJSAtOnload() { var element1 = document.createElement("script"); element1.src = "js/jque ...

endless cycle when utilizing useEffect with a mandatory function

I'm currently in the process of creating a custom hook for sorting and filtering tables within a dashboard application. However, I am encountering an issue with an infinite loop when attempting to refetch data after changing sort or filter fields. The ...

PHP and JavaScript: Understanding Variables

I currently have a View containing an Associative Array filled with information on accidents. Users will have the ability to click on a Country. Once clicked, I want to display accident-related data for that specific country. This data is pulled from PHP ...

AngularJS Default Option Selection

I am encountering some difficulties with the preselection of a select-input in angularJS. The select-box is being populated by an array. <select class="form-control" ng-model="userCtrl.selected_country" ng-options="country.name for country in userCt ...

TypeScript implementation of a reusable component for useFieldArray in React Hook Form

I'm currently working on a dynamic form component using react-hook-form's useFieldArray hook and facing issues with setting the correct type for field. In order to configure the form, I have defined a type and default values: export type NamesAr ...

Delete the item if the link uses Javascript: void(0)

<a class="slicknav_item" href="home">Home<span></span></a> <a class="slicknav_item" href="about">About<span></span></a> <a class="slicknav_item" href="javascript: void(0)">Services<span></span& ...

Attempting to trigger CSS transitions using JavaScript will not be successful

I'm facing an issue where CSS transitions do not work as expected when triggered by JavaScript. let isSearchBarOpen = false; function toggleSearchBar() { if (isSearchBarOpen) { searchBar.style.display = "none"; } else { searchBar.sty ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

Assign the input value to the success callback for the ajax request

I am facing an issue with setting the data returned from a success callback in an AJAX request as an input value. It seems like this problem is arising because I am using the AJAX request within an event function (.on). For updating the specific input, I b ...