Error message in Visual Studio 2017: Identical name 'URLs' declared twice in

In our Visual Studio 2017 project, we have multiple TypeScript files that define a URLs class. Each file contains different implementations of the class to change site URLs based on the specific use case:

customer/urls.ts

namespace Portal {
    export class URLs {
        static homePage(): string { return "/customer"; }
    }
}

supplier/urls.ts

namespace Portal {
    export class URLs {
        static homePage(): string { return "/supplier"; }
    }
}

This approach leads to a "Duplicate identifier 'URLs'" error in Visual Studio 2017. The IDE assumes that all TypeScript files will be included in the webpage, causing the conflict. However, since only one file is pulled in for any given page, there is no actual duplicate identifier in the browser. How can this error be resolved in Visual Studio or is there a valid reason behind it?

Answer №1

This situation arises from a combination of factors:

  1. Typescript namespaces, also known as "internal modules," contribute to the global namespace. Starting a file with a non-exported namespace declaration makes that identifier available globally. In contrast, modules (or "external modules") require explicit importing and exporting. Refer to this explanation for more details.

  2. If specific files are not explicitly included or excluded in your tsconfig.json, both definitions for Portal.URLs will be included. According to the tsconfig.json documentation:

In scenarios where "files" and "include" are not defined, the compiler includes all TypeScript (.ts, .d.ts, and .tsx) files within the directory and subdirectories unless specified otherwise using the "exclude" property.

Hence, the duplicate identifier error is caused by the compiler attempting to add the same declaration to the global namespace twice.

The appropriate solution depends on how the class is used and how the decision is made regarding which implementation to utilize.

One possible solution is to avoid namespaces entirely. Instead, you could define a URLs interface, import it where necessary, and then choose between a CustomerURLs or SupplierURLs implementation based on environmental variables or build configurations.

Alternatively, you could create a base tsconfig.json and use extends to generate separate configuration files like tsconfig.customer.json or tsconfig.supplier.json. In each individual file, exclude all **/urls.ts files except for the relevant one. However, this approach may not be very scalable, and its impact on VS's intellisense functionality is unclear.

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 could be causing the TypeScript type error within this Effector effect subscriber?

Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend: export const deleteItemFX = createEffect({ handler: (id: string) => { return ...

Failed to decipher an ID token from firebase

I'm feeling extremely frustrated and in need of assistance. My goal is to authenticate a user using Google authentication so they can log in or sign up. Everything worked perfectly during development on localhost, but once I hosted my app, it stopped ...

New Entry failing to appear in table after new record is inserted in CRUD Angular application

Working with Angular 13, I developed a basic CRUD application for managing employee data. Upon submitting new information, the createEmployee() service is executed and the data is displayed in the console. However, sometimes the newly created entry does no ...

`mat chip component in Angular Material is malfunctioning`

Whenever I input a string, it does not display properly within the designated textbox. HTML <mat-form-field class="favorite-fruits"> <mat-label>Favorite Fruits</mat-label> <mat-chip-list #chipList aria- ...

Utilize PrimeNG's async pipe for lazy loading data efficiently

I have a significant amount of data (400,000 records) that I need to display in a PrimeNG data table. In order to prevent browser crashes, I am looking to implement lazy loading functionality for the table which allows the data to be loaded gradually. The ...

NativeScript: TypeScript for Formatting Numbers

Being a beginner in NativeScript, I'm finding it difficult to find basic information through Google search. But now, I have a specific question: I have the number 1234567.89 stored in a variable, and I want to display it in a label with the format ...

Sharing references in React Native using TypeScript: The (property) React.MutableRefObject<null>.current is potentially null

I'm working on a React Native form with multiple fields, and I want the focus to move from one field to the next when the user validates the input using the virtual keyboard. This is what I have so far: <NamedTextInput name={&apo ...

Leveraging TypeScript to call controller functions from a directive in AngularJS using the "controller as"

I've encountered an issue while trying to call a controller function from a directive, specifically dealing with the "this" context problem. The logService becomes inaccessible when the function is triggered by the directive. Below is the code for th ...

Identifying the state type within the scope of TypeScript

For my project involving BMI calculation, I want to store the results in an array within a state and keep them locally. export type BmiContextState = { weight: number | undefined; height:number | undefined; open:boolean|undefined; alert:boo ...

What is the best way to incorporate an exported TypeScript class into my JavaScript file?

One of my JavaScript files is responsible for uploading a file to Microsoft Dynamics CRM. This particular JavaScript file makes use of RequireJS to reference another JavaScript file. The referenced JavaScript file, in turn, was compiled from multiple Typ ...

Incorporate a typescript library into your Angular application

Recently, I added a text editor called Jodit to my angular application and faced some challenges in integrating it smoothly. The steps I followed were: npm install --save jodit Inserted "node_modules/jodit/build/jodit.min.js" in angular.json's bui ...

What is the best way to allocate string types from an enum using Typescript?

Within my code, I have an enum that includes a collection of strings export enum apiErrors { INVALID_SHAPE = "INVALID_SHAPE", NOT_FOUND = "NOT_FOUND", EXISTS = "EXISTS", INVALID_AUTH = "INVALID_AUTH", INTERNAL_SERVER_ERROR = "INTERNAL_ ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

Another return payload failing to retrieve the return value

I'm currently facing an issue where a function that should return a value is not being passed on to another function. Below is the code snippet in question: public _getProfileToUpdate() { return { corporateId: this.storeService.setStoreData().p ...

I'm experiencing some difficulties utilizing the return value from a function in Typescript

I am looking for a way to iterate through an array to check if a node has child nodes and whether it is compatible with the user's role. My initial idea was to use "for (let entry of someArray)" to access each node value in the array. However, the "s ...

How to target a particular Textfield in React with its unique identifier

I'm working on a component that contains various Textfields and need to access specific IDs. For example, I want to target the textfield with the label 'Elevator amount'. I attempted the following code snippet but am unsure of how to correct ...

Show the value in Angular in a dynamic way

My template needs to display the text 'Passed' only if item.name === 'michael' is not true. The component receives data in an array called courses[] from its parent. There are two interfaces, Courses and Teachers, where each course ID h ...

Guide on setting up next-auth for external API login in a Next.js 13 app directory

Hey there, I'm currently working on setting up a login system with next-auth in Next.js 13 using appDir: true. The version of Next.js I am using is 13.3.0, but after going through the documentation, I must admit that I'm struggling to fully grasp ...

When using VS Code, custom.d.ts will only be recognized if the file is currently open in the

I have created some custom Typescript declarations in a custom.d.ts file. When I have this file opened in VS Code, everything works correctly and the types are recognized. However, when I close the file, VS Code does not recognize these definitions, leadin ...

Something went wrong in the prerender.ts file at line 7. The error message is indicating that it cannot locate the module './dist-prerender/main.bundle'

Encountering an error while compiling the Angular code for prerendering: ERROR in prerender.ts(7,62): error TS2307: Cannot find module './dist-prerender/main.bundle' npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] b ...