Ways to expand the interface of an external Typescript library that includes special characters in the name?

I have encountered a question similar to this before, but I couldn't locate one specifically pertaining to special characters such as @ and / within namespaces.

Scenario:

I am looking to enhance the

import { Strapi } from '@strapi/strapi';
interface of Strapi from @strapi/strapi. It lacks the webhookStore and other properties that I want to include.

Initial approach

I created a file named extensions.d.ts with the following content

declare global {
    namespace '@strapi/strapi' {
        interface Strapi {
            webhookStore: {
                c: any;
            };
        }
    }
}

Unfortunately, it did not work. Typescript raised an error TS1003: Identifier expected. for '@strapi/strapi'

https://i.sstatic.net/Sa2PB.png

In the past, I successfully extended interfaces with single names like "Stripe", however, in this scenario, I am unsure how to proceed.

I cannot use @strapi/strapi without encasing it in ' as it leads to compilation errors.

Alternate approach - module augmentation/merging

I also attempted the concept of module augmentation suggested here, but it was unsuccessful.

type WebhookStore = {
    findWebhooks: () => void;
};

declare module '@strapi/strapi' {
    interface Strapi {
        webhookStore: WebhookStore;
    }
}

This essentially redeclares the Strapi interface and only recognizes webhookStore as the sole property! (losing information about other properties exported by the library itself). Furthermore, it fails to compile as the ts compiler only acknowledges webhookStore. It is simply redeclaring without merging.

As a result, numerous errors like this occur during yarn build, which involves linting and compiling

5 import { factories } from '@strapi/strapi';
           ~~~~~~~~~
src/api/tag/routes/tag.ts:5:10 - error TS2305: Module '"@strapi/strapi"' has no exported member 'factories'.

Answer №1

If you're interested in declaration merging or module augmentation, I can guide you through the process. To enhance a module, follow these steps -

import API from "@strapi/strapi";

declare module "@strapi/strapi/lib/types/core/index" {
    interface Strapi {
        webhookStore: { c: any }
    }
}

declare global {
  namespace Strapi {
    export type Webhook = { c: any };
  }
}

const store = API({}).webhookStore
 //   ^? const store: { c: any; }

let a: Strapi.Webhook
//  ^? let a: Strapi.Webhook

For further experimentation, visit this playground link;

Answer №2

Creating a namespace with the name @strapi/strapi is not feasible, as it does not comply with the rules for valid TypeScript or ECMAScript identifiers.

In order to accurately represent global ECMAScript objects, namespaces must adhere to the requirements of being valid TypeScript / ECMAScript identifiers.

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

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

Building unique queries using TypeScript and React testing-library

I am currently working on creating a custom query specifically for Testing Library in TypeScript to be used with a React project. The custom query is designed to retrieve the first th cells within the tbody of the container: // all-table-headings.ts - cust ...

Unable to locate module within Typescript

Hello everyone, I am facing a problem similar to this one: I have an app written in TypeScript, and within it, I have imported import { Component } from '@angular/core'; import {CORE_DIRECTIVES} from '@angular/common'; import { MODA ...

ngOnInit unable to properly listen to event stream

I've been trying to solve a persistent issue without success. The problem involves the interaction between three key elements: the HeaderComponent, TabChangingService, and TabsComponent. Within the HeaderComponent, there are three buttons, each with a ...

angular8StylePreprocessorSettings

I'm currently trying to implement the approach found on this tutorial in order to import scss files through stylePreprocessorOptions in Angular 8. However, I'm encountering an error stating that the file cannot be found. Any suggestions on how to ...

Steer clear of using enum values in typescript to prevent potential issues

I am looking to iterate through an enum type in order to populate options within a react component. Below, you will find the specific enum and a function that retrieves its keys and values. export enum TaskType { daily, weekly, monthly, yearly } ...

What is the best way to persist form state in an Angular Lazy Loading Module?

I've set up 2 routes in my Angular 7 application, { path: 'create', component: CreateComponent }, { path: 'view', component: ViewComponent } Both of these routes are lazily loaded. The CreateComponent contains a f ...

Experiencing constant errors with axios requests in my MERN Stack project using a Typescript Webpack setup

Hey there, I'm in need of some help! I've been working on a MERN Stack project and have set up Webpack and Babel from scratch on the frontend. However, every time I send a request to my Node Server, I keep getting an error message back. Can anyon ...

When passing an invalid value to the Props in TypeScript, no errors are being thrown

const enum ColumnValues { one = 1, two = 2, three = 3, } interface Props { style?: StyleProp<ViewStyle>; title?: string; titleContainerStyle?: StyleProp<ViewStyle>; titleStyle?: StyleProp<TextStyle>; textInputStyle?: Styl ...

Interactive feature on Google Maps information window allowing navigation to page's functions

Working on an Angular2 / Ionic 2 mobile App, I am utilizing the google maps JS API to display markers on a map. Upon clicking a marker, an information window pops up containing text and a button that triggers a function when clicked. If this function simpl ...

To implement a filter in MongoDB, make sure to specify a function argument before

Utilizing TypeScript, Node.js, Mongoose, and MongoDB in my project. I have a function that resembles the following: async function getAllBooks(title?: string, authorName?: string, sortBy?) { const books = await bookModel.find().sort(); return book ...

Error: Unable to access property 'camera' as it is undefined

After implementing the Raycaster from Three js to detect collision following a MouseMove event, I encountered an error: Cannot read properties of undefined (reading 'camera') Here is the code snippet causing the issue: bindIFrameMousemove(if ...

After compilation, what happens to the AngularJS typescript files?

After utilizing AngularJS and TypeScript in Visual Studio 2015, I successfully developed a web application. Is there a way to include the .js files generated during compilation automatically into the project? Will I need to remove the .ts files bef ...

React-bootstrap-table Axios delete operation causing [object%20Object] to be displayed in the browser console

I am having trouble executing a delete operation using axios on a react-bootstrap-table, and encountering this error in the console DELETE http://localhost:9000/api/terminals/[object%20Object] Uncaught (in promise) Error: Request failed with status cod ...

What is the correct way to handle Vue props that include a dash in their name?

I am currently working on a project using Vue. Following the guidelines of eslint, I am restricted from naming props in camel case. If I try to do so, it triggers a warning saying Attribute ':clientId' must be hyphenated. eslint vue/attribute-hyp ...

Despite being listed in the entry components, HelloComponent is not actually included in the NgModule

Check out my StackBlitz demo where I am experimenting with dynamically instantiating the HelloComponent using the ReflexiveInjector. The HelloComponent is added to the app modules entryComponents array. Despite this setup, I am still encountering the foll ...

Refreshing DataTables with specific parameters using ajax.reload()

In my Angular2 project, I am utilizing DataTables with the serverSide feature. After making changes, I am attempting to reload the table and pass these changes as parameters in a POST request via AJAX. The issue I am encountering is that DataTables alway ...

Error: Axios encountered an issue with resolving the address for the openapi.debank.com endpoint

After executing the ninth command to install debank-open-api, I encountered an error while running the code in my index.js file. To install debank-open-api, I used the following command: npm install debank-open-api --save Upon running the following code ...

Attempting to transfer information between components via a shared service

Currently, I am utilizing a service to transfer data between components. The code snippet for my component is as follows: constructor(private psService: ProjectShipmentService, private pdComp: ProjectDetailsComponent) { } ngOnInit() { this.psSe ...

Is it considered beneficial to use Observable as a static class member?

Lately, I have been diving into a new Angular project and noticed that the common way to share state between unrelated components is by using rxjs Subject/BehaviorSubject as static members within the class. For instance: export class AbcService { privat ...