TS2304: Cannot find name 'X'
What’s happening?
Section titled “What’s happening?”This error occurs when TypeScript cannot find a variable, function, or type in the current scope.
Reproduction
Section titled “Reproduction”console.log(myVariable);// ❌ Cannot find name 'myVariable'Solutions
Section titled “Solutions”Option 1: Declare the variable
Section titled “Option 1: Declare the variable”const myVariable = "Hello";console.log(myVariable); // ✅Option 2: Import from another module
Section titled “Option 2: Import from another module”import { myVariable } from './config';console.log(myVariable); // ✅Option 3: Add type declarations for global variables
Section titled “Option 3: Add type declarations for global variables”declare const myGlobal: string;
// Now usable everywhereconsole.log(myGlobal); // ✅Common scenarios
Section titled “Common scenarios”Missing imports
Section titled “Missing imports”const result = axios.get('/api');// ❌ Cannot find name 'axios'
// ✅ Fix:import axios from 'axios';Using browser APIs without lib
Section titled “Using browser APIs without lib”// tsconfig.json missing "dom" in libconst element = document.querySelector('div');// ❌ Cannot find name 'document'
// ✅ Fix tsconfig.json:{ "compilerOptions": { "lib": ["ES2022", "DOM"] }}Key takeaways
Section titled “Key takeaways”- Always import before using
- Check
tsconfig.jsonfor missinglibentries - Use
.d.tsfiles for global declarations