typescript declaring a namespace with a restricted identifier

I have created a custom Http client in typescript with the following definition:

declare namespace Http {
   type HttpOptions = ...;
   type HttpPromise<T> = ...

   function get<T>(url: string, options?: HttpOptions): HttpPromise<T>;
   function delete<T>(url: string, options?: HttpOptions): HttpPromise<T>;
}

The issue arises with the use of delete as it is a reserved word. However, I require the method Http.delete('/foo') for my module.

How can I declare this dependency without causing conflicts?

Answer №1

Perhaps you'd prefer not to receive the advice of "don't do that," but it might be the most sound recommendation. Utilizing reserved words as identifiers doesn't always lead to failure, however, encountering issues in certain JavaScript environments is a possibility. Nevertheless, let's proceed anyway.


This situation presents an interesting conundrum. I would like to employ a quoted string literal similarly to how one would use with a method or property name, as stated in the TypeScript specification:

String literals may be used to give properties names that are not valid identifiers

But unfortunately, this approach does not apply to naming functions, which must adhere to valid identifier rules.

An alternative option appears to involve assigning the function a valid name and then exporting an alias for it:

declare namespace Http {
  export type HttpOptions = ...
  export type HttpPromise<T> = ...
  export function get<T>(url: string, options?: HttpOptions): HttpPromise<T>;
  function del<T>(url: string, options?: HttpOptions): HttpPromise<T>;  
  export { del as delete }; // no error
}

The process seems feasible, although documentation supporting this method is currently scarce. Initially, one might assume that using a reserved word within the as clause would fail (quoting it also generates an error), but surprisingly, it functions correctly:

Http.get('url') // okay
Http.delete('url') // apparently okay but you probably shouldn't
Http['delete']('url') // okay

Does this clarification assist you?


Another suggestion involves employing declaration merging, though its functionality also raises some eyebrows according to instances of surprise. In this scenario, start by declaring the namespace solely with type aliases, followed by merging a declared constant bearing the same name containing the properties. It may seem fragile and unconventional, but it has proven effective in my case:

declare namespace Http {
  export type HttpOptions = ...
  export type HttpPromise<T> = ...
}
declare const Http: {
  get<T>(url: string, options?: Http.HttpOptions): Http.HttpPromise<T>;
  "delete"<T>(url: string, options?: Http.HttpOptions): Http.HttpPromise<T>;  
}

I hope one of these approaches proves beneficial to you; I wish you the best of luck!

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

Typescript monorepo facing issues with module resolution in Next.js projects

In my monorepo with yarn workspaces, I have 2 Next.js projects set up. apps ┣ app-1 ┗ app-2 The problem arises when app-1 needs to import components from app-2. I add app-2 as a dependency in the app-1 project and configure the path in app-1's ...

What could be causing my TypeScript code to not be recognized as CommonJS?

I rely on a dependency that is transpiled to ES6. My goal is to leverage ES2019 features in my own code. Ultimately, I aim to output ES6. This is how I set up my tsconfig { "compilerOptions": { "module": "CommonJS" ...

Version 4.0 of Electron-React-Boilerplate has encountered an error: The property 'electron' is not recognized on the type 'Window & typeof globalThis'. Perhaps you meant to use 'Electron' instead?

I encountered an error while attempting to call the IPCrenderer using the built-in context bridge. The error message reads as follows: Property 'electron' does not exist on type 'Window & typeof globalThis'. Did you mean 'Elect ...

"Implementing autocomplete feature with initial data in Angular 4 using FormControl

I have incorporated material.angular.io components into my app, particularly autocomplete. I am customizing it to function as a multi-select, but I am encountering an issue with loading initial values: export class CaseActivityTimeEditComponent implements ...

Set S3 Bucket Policy to include ELB Account

After utilizing the AWS console to create a bucket for access logging via the load balancer edit attributes screen, I am now in the process of transforming this action into CDK code using TypeScript. This allows me to automate the creation of new S3 bucket ...

Customize the color of the Material-UI Rating Component according to its value

Objective I want to dynamically change the color of individual star icons in a Ratings component (from material-ui) based on the value selected or hovered over. For example, hovering over the 1st star would turn it red, and hovering over the 5th star woul ...

"Encountered an error: 'Invalid private class xy' in the process of constructing an Angular library

Currently, I am in the process of creating an npm package using Angular. In the midst of building the library, I encountered the following error: An unexpected issue with the private class MyLibComponent has surfaced. While this class is accessible to us ...

JavaScript: Manipulating Data with Dual Arrays of Objects

//Original Data export const data1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: &a ...

In the realm of Typescript Angular, transferring the value of an object's property to another property within the

I'm working with a large TypeScript object and I am hoping to automate certain parts of it to streamline my workflow. myObject = [ { id: 0, price: 100, isBought: false, click: () => this.buyItem(100, 0) } buyItem (it ...

Updating an element within a for loop using Angular TypeScript

I'm trying to figure out how to update the value of an HTML DOM element that is bound from a TypeScript file in each iteration of a for loop, rather than at the end of the loop. I want to see all values as the loop is running. For example, imagine I ...

Leveraging Class Types with Generics

Take a look at this example: https://www.typescriptlang.org/docs/handbook/2/generics.html#using-class-types-in-generics To make it work, I just need to call a static method before instantiation. Let's adjust the example like this: class BeeKeeper { ...

What is the functionality of observable in Angular? The 'includes' property is not present in the 'Observable' type

I am currently diving into the world of Angular5 and I have been using Firebase to fetch data for my page display. While researching how to retrieve data from Firebase using AngularFire, I found that many examples were outdated. Eventually, I learned that ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

How to effectively send an HTTP GET request to a REST API in Angular 2 and save the response in a JSON object

Currently, I am attempting to execute a GET request to the GitHub API using Angular2. The returned data is in JSON format, and my goal is to store it in a JSON object for further processing. While referring to the Angular2 documentation for guidance, I en ...

Using object in TypeScript to reduce arrays

Is there a way to set the return value for my reducer in TypeScript? I am looking to achieve: Instead of using 'any', what should I assign as the type for acc? How can I define my return type so that the output will be {temp: 60, temp: 60}? retu ...

Javascript's callback mechanism allows functions to be passed as arguments

I am currently delving into the intricacies of the callback mechanism in javascript, particularly typescript. If I have a function that expects a callback as an input argument, do I need to explicitly use a return statement to connect it with the actual ca ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

Can the script be loaded into a TypeScript file?

I'm currently in the process of integrating this script tag into my Angular 2 project, but I'm searching for a way to incorporate it into the typescript file so that I can access its methods within the .ts file. <script type="text/javascript" ...

ERROR UnhandledTypeError: Unable to access attributes of null (attempting to retrieve 'pipe')

When I include "{ observe: 'response' }" in my request, why do I encounter an error (ERROR TypeError: Cannot read properties of undefined (reading 'pipe'))? This is to retrieve all headers. let answer = this.http.post<ResponseLog ...