I am looking for the most optimal method to export a TypeScript class from my package in a way that allows it to be extended by other packages

In the process of developing a TypeScript library package called 'MyPkg,' I have created some classes (such as 'MyPkgClass') located in a specific sub-directory [e.g., src/path/to/mypkg] with essential functionality.

The goal is for another package, named 'OtherPkg,' to extend 'MyPkgClass' and add any additional features as needed. This allows me to provide basic features that I can modify or enhance in the future.

During local testing using 'npm link' in 'OtherPkg,' I realized that importing 'MyPkgClass' was problematic:

import MyPkgClass from “MyPkg/bin/<path>/<to>/MyPkgClass”

This method would restrict my ability to move or rename the file/class later on, which is not ideal. While I could create a different class at a fixed location under 'bin' and extend it from 'MyPkgClass' to prevent breaking 'OtherPkg,' this approach seems like poor design.

What is the correct way to expose 'MyPkgClass'? Should I re-export it from Index.ts of MyPkg? Or should I export 'MyPkgClass' as a type?

I am seeking guidance on standard TypeScript documentation or examples for assistance as a newcomer facing these challenges. I have attempted to search TypeScript documentation without success, possibly due to using incorrect search terms.

Answer №1

When faced with the challenge of importing a package like

Import MyPkgClass from “MyPkg/bin/<path>/<to>/MyPkgClass”

You can streamline this process by exporting it from index.ts located at the root of your sub-project MyPkg, as shown below:

MyPkg/index.ts

export * from './bin/<path>/<to>/MyPkgClass”';

Then, in another module where you wish to utilize it,

import MyPkgClass from 'MyPkg';

Take a look at for more information.

For extending the base class simply follow these steps:

class OtherPkgClass extends MyPkgClass {
  constructor(someParameter: String) {
    super(someParameter);
  }

  private newMethod() {
    ...
  }
}

Visit https://www.typescriptlang.org/docs/handbook/classes.html#inheritance to learn more about inheritance in TypeScript.

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

Clear pagination - results generated by the clr-dg-page-size component

I'm currently developing an Angular 8 application using Clarity UI. Within my app, I have implemented a datagrid with pagination. My challenge lies in fetching data after changing the number of items per page, as there is no output provided by the Cl ...

Encountered Runtime Issue of TypeError: undefined cannot be iterated (unable to access property Symbol(Symbol.iterator))

I've been working on a multiselect feature in my Next.js project, utilizing states and setting them accordingly. However, I keep encountering this specific error: https://i.stack.imgur.com/m8zuP.png whenever I click on this: https://i.stack.imgur.c ...

Enumerated types in Typescript: access the values

Below is a flagged enum I have: enum PermissionEnum { SU = 1 << 0, // 1 Administrator = 1 << 1, // 2 User = 1 << 2 // 4 } If the value given is 6, how can I achieve: An array of strings -> ['Adm ...

Issues with the File plugin in Ionic 2

Currently, I am working on integrating Quickblox into my Ionic2 application. I have successfully implemented all the required functionalities except for file uploading. In Quickblox, there is a specific function that needs to be used for uploading files, a ...

Enhancing JavaScript functions with type definitions

I have successfully implemented this TypeScript code: import ytdl from 'react-native-ytdl'; type DirectLink = { url: string; headers: any[]; }; type VideoFormat = { itag: number; url: string; width: number; height: number; }; type ...

Error: The slick function is not recognized by _this.$instance

I have implemented the ngx-slick-carousel in my Angular project for creating a slider. However, I encountered an error when I navigate to the component containing the slider, resulting in the following error displayed in the console: ERROR TypeError: _t ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

A guide on connecting multiple select components to a unified Angular 6+ reactive form without triggering redundant updates

I am facing an issue where I need to connect multiple input components to a single angular reactive form, but encounter two main obstacles: By default, only the form in which user input occurs gets updated If I use [(ngModel)] it does work, but it trigge ...

What's the quickest method for duplicating an array?

What is the quickest method for duplicating an array? I wanted to create a game, but I found that Array.filter was performing too slowly, so I developed a new function: Array.prototype.removeIf = function(condition: Function): any[] { var copy: any[] ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

The 'string' type in React Child does not have a '.__docgenInfo' property available

When passing children to a React component and trying to determine if a 'Button' type component is among them, I used the following code snippet. export type ExampleComponentProps = { children: React.ReactNode; } export const ExampleComponent: ...

What is the equivalent of a "Class" in Typescript for defining an "Interface"?

I am interested in passing "Interfaces" to a function. Not just a specific interface, but any interfaces. As explained here, for Class, I can handle it as a type. export type ClassType<T> = { new(...args: any[]): T }; function doSomethingWithAnyCla ...

Enhance Component Reusability in React by Utilizing Typescript

As I embark on developing a React application, my primary goal is to keep my code DRY. This project marks my first experience with Typescript, and I am grappling with the challenge of ensuring reusability in my components where JSX remains consistent acros ...

Implementing multer diskStorage with Typescript

I'm currently in the process of converting a node.js server to TypeScript. Here is what my function looks like in Node: const storage = multer.diskStorage({ destination: function (req, file, cb) { const dir = './uploads/'; ...

Learn how to efficiently disable or enable a button in Angular depending on the selected radio button

In order to disable the button when the remarks are marked as failed. Here is an example scenario: Imagine there is an array containing two to four items. First example: ITEM 1 -> FAILED -> Remarks (required) ITEM 2 -> FAILED -> Remarks (r ...

Preventing specific directories from being imported in a Typescript project

I am intrigued by the idea of restricting files within a specific scope from importing files from another scope. Let's consider this example: Imagine we have the following project structure: project/ ├── node_modules/ ├── test/ ├── ...

When using the delete method in Next.js, req.body is undefined

Strangely, I cannot figure out the reason why fetching data and inserting it into the body of my response results in an "undefined" message in the console. Interestingly, I have two nearly identical components - one employing a POST method with a populated ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

Tips for resolving the issue of loading not appearing on screen in Angular

How can I resolve the problem of the loading animation not appearing? Below is the code snippet: HTML <div *ngIf="tempThermometer | async as temp; else loading"> <ng-container *ngIf="temp.length !== 0; else noItems"> &l ...