TypeScript实现链表时遭遇Duplicate identifier 'Node'错误的排查与解决
Let's break down why you're seeing this error and how to fix it—this is a common gotcha with TypeScript when working with generic class names!
Your Code & Issue
You've defined a simple INode interface and Node class for your linked list:
interface INode<T> { data: T; next: INode<T> | null; } class Node<T> implements INode<T> { public data: T; public next: INode<T> | null; constructor(data: T) { this.data = data this.next = null } }
But TypeScript keeps complaining about a "Duplicate identifier 'Node'", even though you don't see duplicates in your code. Here's what's going on:
Common Causes & Solutions
1. Clash with the built-in DOM Node type
The #1 culprit here is that Node is already a reserved type in the browser's DOM API (it represents any element in the HTML document). By default, TypeScript includes all DOM types in browser-targeted projects, so your custom Node class is colliding with this built-in type.
Quick Fix: Rename your class to something more specific
Just pick a name that doesn't overlap with built-in types—LinkedListNode is a great choice:
interface INode<T> { data: T; next: INode<T> | null; } class LinkedListNode<T> implements INode<T> { public data: T; public next: INode<T> | null; constructor(data: T) { this.data = data this.next = null } }
2. Accidental duplicate declarations
Double-check if you've accidentally defined the Node class in another file, or imported it twice in the same scope. For example:
- You might have copied the class into a utility file and forgotten to remove the original.
- A circular import could be causing the class to be loaded twice.
Fix:
- Do a full project search for
class Nodeto spot and remove duplicates. - Audit your imports to ensure you're not importing the same class multiple times in one file.
3. Misconfigured TypeScript settings (for non-browser projects)
If you're working in a Node.js environment (not a browser), your tsconfig.json might still be including DOM types by mistake.
Fix: Adjust your tsconfig.json
Update the lib option to only include the ECMAScript types you need, excluding DOM:
{ "compilerOptions": { "lib": ["ESNext"], // other config options... } }
Alternatively, wrap your linked list code in a namespace to avoid conflicts:
namespace LinkedListUtils { export interface INode<T> { data: T; next: INode<T> | null; } export class Node<T> implements INode<T> { public data: T; public next: INode<T> | null; constructor(data: T) { this.data = data this.next = null } } } // Use it like this: const newNode = new LinkedListUtils.Node("hello");
内容的提问来源于stack exchange,提问作者gabriel_tiso

