Is it possible for me to transfer a change to the worldwide namespace from my library?

I am looking to enhance an existing TypeScript type within the global namespace in my library and then expose it for use in other projects. Can this be done?

Below is my current code:

Promise.ts

Promise.prototype.catchExtension = function<T>(this : Promise<T>): Promise<T> {
    return Promise.prototype.catch.apply(this, [() => { /*do stuff*/ }]);
}

Promise.d.ts

declare global {
    interface Promise<T> {
        catchExtension(): Promise<T>;
    }
}
export { }

How can I utilize this in another application that references my library? Since it was exported without a name using export { }, I cannot use import { .... } from '@mylib'.

Answer №1

If you want to simply execute the file without importing any specific modules, you can achieve this by using the following code:

import '@mylib'

This will run the file in a separate scope from the module where it is being imported, but it should work without any issues since you are making modifications at the global level.

Answer №2

After some experimentation, I have finally discovered a solution to the problem. I am sharing it here in case it can help others as well.

The key was to include both the declaration and definition in the .ts file and then import the file (anywhere!) in the library. This allowed my other project to access the extension method as soon as it imported anything from the library.

Here is the updated code:

Within the library project:

Promise.ts

Promise.prototype.catchExtension = function<T>(this : Promise<T>): Promise<T> {
    return Promise.prototype.catch.apply(this, [() => { /*do stuff*/ }]);
}

declare global {
    interface Promise<T> {
        catchExtension(): Promise<T>;
    }
}
export { }

lib.ts

import './Promise'; // this line can be placed in any file within the library...
export { } from './Promise';
// Additional exports
export { Example } from './Example';

Within the main app:

// Import anything from the library
import { Example } from '@mylib';

const x: Promise<string> = new Promise( (resolve, reject) => { reject(); });
x.catchExtension();
// The extension method works as expected

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

What is the most effective method for declaring callbacks on objects in Typescript?

I am currently working on a sidebar menu component that is connected to a service holding items in the menu. This allows multiple sources to make alterations to the menu as needed. Each item in the menu currently follows the SidebarItem interface: export ...

Error: The template could not be parsed due to the following issues: Element 'mat-card' is not recognized

Every time I run Karma "ng test" for my project, an error keeps popping up: Error message: Failed - Template parse errors: 'mat-card' is not a known element Interestingly enough, the application seems to work perfectly fine with the mat-card ta ...

Can a before hook ever run after a test in any situation, Mocha?

My before hook runs after the initial test and at the conclusion of the second test. Here is the code for my before hook: before(function () { insightFacade.addDataset("courses", content) .then(function (result: InsightResponse) { ...

TypeScript: Seeking a mechanism akin to ReturnType<...> that specifically targets the type of the initial function parameter

Can TypeScript allow for the declaration of a ReturnType<...> that doesn't fetch the return value's type but instead retrieves the type of the first argument? type SingleArgFunction<A, R> = (arg: A) => R // incorrect - how can th ...

When using a Redux action type with an optional payload property, TypeScript may raise complaints within the reducer

In my react-ts project, I define the following redux action type: type DataItem = { id: string country: string population: number } type DataAction = { type: string, payload?: DataItem } I included an optional payload property because there are tim ...

The functionality of NgbModal in ng-bootstrap is experiencing issues and becoming unresponsive in ng-bootstrap version 15 and Angular version 16

Currently, I am in the process of upgrading my Angular app from version 15 to version 16. Following the documentation, I have updated the @ng-bootstrap/ng-bootstrap package to version 15. However, after this update, I am facing issues with the NgbModals no ...

Mapping two objects of the same shape to each other recursively using TypeScript

I receive regular data from a specific source. This data consists of nested objects containing numerical values. For example: { a: 1, b: { c: 2, d: 3.1, }, } My objective is to organize this data into multiple TimeSeries objects of the same struct ...

Generic Typescript abstract method error: "the class specifies the property as an instance member, but the extended class defines it as an instance member function."

Upon exploring the code in this playground link, abstract class Base<F extends () => void> { public abstract __call__: F; } type CallSignature<T> = { (): T; (value: T): void; } class Foo<T> extends Base<CallSignature&l ...

Organize by a collection of strings or a collection of enums

Here is a list of objects that I have: enum MealType { Breakfast, Lunch, Dinner } interface FoodItem { name: string, type: MealType[], } const foodItems: FoodItem[] = [ { name: 'Pizza', type: [MealType.Lunch, MealType.Dinner ...

When the first element of an array is undefined, Angular's ngFor will not render anything

We have an array called stringArray: var stringArray = new Array(); stringArray[1] = 'one'; In Angular, the ngFor directive displays nothing when stringArray[0] is undefined. How can this issue be resolved? ...

Guide on extracting the id from the path parameter in an HTTP request using Cloud Functions and nodejs

I am currently in the process of developing a serverless application using GCP Cloud Functions (nodejs). I have successfully implemented different behaviors based on the request method, but I am facing an issue with retrieving the id from the path paramete ...

Can one utilize generic parameter value within a conditional type result field in Typescript?

Trying to create a versatile function type for data transformation can be a bit tricky. When dealing with a single object, it's straightforward: export type SingleObjFunction<InputDataType, OutputDataType> = (object: InputDataType) => Outpu ...

While attempting to index a nested object, TypeScript (error code 7053) may display a message stating that an element implicitly carries the 'any' type due to the inability to use an expression of type X to index type

I'm encountering an issue in TypeScript where I get the error (7053): Element implicitly has an 'any' type because expression of type X can't be used to index type Y when trying to index a nested object. TypeScript seems to struggle wit ...

"Define a TypeScript function type that can return either an object or a string depending on whether it succeeds or fails

I encountered an issue with a function that either returns a Promise on success or a string on error. async create(createDebtorDto: CreateDebtorDto): Promise<Debtor> { console.log("createDebtorDto", createDebtorDto) try{ const createdD ...

The @angular/fire package is unable to locate the AngularFireModule and AngularFireDatabaseModule modules

I am facing some challenges while trying to integrate Firebase Realtime Database into my Angular project. Specifically, I am encountering difficulties at the initial step of importing AngularFireModule and AngularFireDatabaseModule. To be more specific, I ...

activeStyle is not a valid property for type 'IntrinsicAttributes'

I encountered an issue while attempting to utilize NavLink in a react typescript project. The error message states: "Property 'activeStyle' does not exist on type 'IntrinsicAttributes & NavLinkProps & RefAttributes'." import Rea ...

Error in sending data to the server via the specified URL: "Http failure response for http://localhost/post.php: 0 Unknown Error" and POST request to http://localhost/post.php failed with error code

Feeling a bit stuck trying to add data to my database. As a junior with PHP and Angular, I am using PHP via XAMPP and Angular 8. Is it possible to create separate files for the post and get methods in the PHP file? app.component.ts import { Component, O ...

Storing the selected value from dynamically generated options in Angular using ngFor

I have a collection of items called Fixtures. Each fixture contains a group of items named FixtureParticipants. Here is my process for generating choices: <tr *ngFor="let fixture of fixtures$ | async; let i=index"> <th scope="row& ...

Switching a class component to a functional component with react hooks (specifically useRef) - tips for preventing the dreaded "undefined" error

I have a code snippet that works as a class component and I'm trying to convert it into a functional component using the react-rewards library. Class component (working): import { Checkbox } from "@chakra-ui/react"; import React, { Compone ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...