How to fix the "duplicate identifier" error in TypeScript

When working with TypeScript, there is a big chance that you will have to deal with a “duplicate identifier” error sooner or later.

But what exactly this error means? Read the error text again. Duplicate identifier. You are defining, with other words referencing, the same identifier (class, method, property) twice in your code.

The error looks like this in Visual Studio:

The duplicate identifier error in TypeScript

In my case, the one file that was involved in the error was always a d.ts file. You can find more information about d.ts files here.

In my code this d.ts file is always the d.ts file that Visual Studio automatically generates when I build my TypeScript project. This file contains all the declarations of classes and interfaces that are defined in my code. You can activate this option in the TypeScript preferences of your project:

Generate declaration files in TypeScript

So, you have the first clue. The d.ts file of your project contains the one definition. But which file contains the second?

In the Error List of Visual Studio you can see the second file that throws the same error. Usually this file is a file in another project, that references the d.ts file of the first project. Go to this file and double check the ///<reference path=”…” /> rows that you most probably have added at the top of the file.

Are these references reference a .ts file directly which its structure is also declared in the external d.ts file?

If the answer to the previous question is yes, then you just found the reason to the “duplicate identifier” error. Remove the lines that declare a class/ property/ function twice since you already have the reference to the external d.ts file.

That’s it, the error is now gone and you can build the complete solution again.

Other reasons responsible for the duplicate identifier error

If you structure your code into multiple Visual Studio projects, then there is often the case that you accidentally defined a class twice, and as a result the properties of the class are declared twice. If then these classes are contained inside the same namespace or module and the definitions (d.ts files) of their projects are loaded together, then you will see the “duplicate identifier” error. Just remove or rename the one class.

comments powered by Disqus