VS2017中TypeScript出现“Duplicate identifier 'URLs'”错误求助
解决TypeScript中重复标识符"URLs"的问题
这个问题的核心原因是:TypeScript的命名空间会在编译后合并同名的命名空间对象,你在customer/urls.ts和supplier/urls.ts里都在Portal命名空间下定义了URLs类,导致编译时触发重复标识符错误。下面是几种针对性的解决方案,你可以根据项目结构选择:
方案1:使用ES模块(推荐)
这是TypeScript官方推荐的模块化方式,通过文件模块实现隔离,从根源避免命名空间冲突:
修改urls.ts文件
customer/urls.ts:
// 移除命名空间,直接导出类 export class URLs { static homePage(): string { return "/customer"; } }
supplier/urls.ts:
export class URLs { static homePage(): string { return "/supplier"; } }
在使用时区分导入
通过导入别名来区分两个同名类:
import { URLs as CustomerURLs } from './customer/urls'; import { URLs as SupplierURLs } from './supplier/urls'; // 调用对应方法 console.log(CustomerURLs.homePage()); // 输出 "/customer" console.log(SupplierURLs.homePage()); // 输出 "/supplier"
这种方式符合现代JavaScript模块规范,结构更清晰,也更容易和Webpack等打包工具配合,适合大多数现代项目。
方案2:使用子命名空间
如果你更倾向于保留命名空间的结构,可以在Portal下创建子命名空间来区分不同业务模块:
修改urls.ts文件
customer/urls.ts:
namespace Portal.Customer { export class URLs { static homePage(): string { return "/customer"; } } }
supplier/urls.ts:
namespace Portal.Supplier { export class URLs { static homePage(): string { return "/supplier"; } } }
在使用时调用对应子命名空间的类
console.log(Portal.Customer.URLs.homePage()); console.log(Portal.Supplier.URLs.homePage());
这种方式保持了命名空间的层级关系,适合习惯用命名空间组织代码的传统项目。
方案3:类的静态成员合并(不推荐当前场景)
如果你的需求是扩展URLs类而不是提供完全不同的实现,TypeScript支持合并类的静态成员,但这显然不符合你"根据引入文件切换站点URL"的核心需求,仅作补充说明:
// customer/urls.ts namespace Portal { export class URLs { static customerHome(): string { return "/customer"; } } } // supplier/urls.ts namespace Portal { export class URLs { static supplierHome(): string { return "/supplier"; } } } // 使用时可以访问两个静态方法 console.log(Portal.URLs.customerHome()); console.log(Portal.URLs.supplierHome());
这种方法无法实现"切换URL"的需求,因此不推荐在你的场景中使用。
内容的提问来源于stack exchange,提问作者Jez
相关产品推荐
相关产品推荐

