Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript class with same name duplicate in different files

I have a project (nodejs) written in typescript I got two file that define User class, none of the is exported and though they are isolated i get duplicate error from the typescript compiler on both of these files

examples/hello_world.ts(3,7): error TS2300: Duplicate identifier 'User'. 
examples/models/user.model.ts(2,7): error TS2300: Duplicate identifier 'User'.

Any ideas? Thanks

like image 565
Dimkin Avatar asked Apr 19 '17 09:04

Dimkin


2 Answers

Due to compatibility with web-platform TypeScript-team decided to treat scripts without explicit imports and exports as just plain scripts:

Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).

https://www.typescriptlang.org/docs/handbook/modules.html#introduction

For environments like Node.js, it is not so convinient. There is an issue in the TypeScript repo regarding this https://github.com/microsoft/TypeScript/issues/18232.

like image 99
Alexander Myshov Avatar answered Oct 31 '22 17:10

Alexander Myshov


How to force a source file to be a module

If your source file doesn't contain any top level import or export, just add the following line:

export {};

Notice: There is a proposal on this subject but currently in stage 1, we have to wait.


Original answer: Use classic imports and exports

Use the ES6 syntax for modules, with import and export:

// models/user.model.ts
export class User {
}

// hello_world.ts
import { User as UserModel } from "./models/user.model"
export class User {
}

See the section "Renaming imports and exports" in the article: ES6 In Depth: Modules, from Mozilla.

like image 21
Paleo Avatar answered Oct 31 '22 18:10

Paleo