How to fix Cannot find name 'X' in TypeScript
This TypeScript compiler error occurs when you reference a variable, type, class, or function that hasn't been declared or imported. The fix involves declaring the name, importing it from another module, or fixing typos.
Quick fix
Fixes TS2304
const myVar = "hello";
const myFunction = () => {};
type MyType = { name: string };- Check if the identifier is defined
- Check if you need to import the name
- Fix typos and case sensitivity
- Install missing type definitions for third-party packages
const myVar = "hello";const myFunction = () => {};type MyType = { name: string };Cannot find name 'X'
What this error means
TypeScript is a statically-typed language that requires all identifiers to be declared before they can be used. When the TypeScript compiler encounters a name that it cannot resolve—either because it's not declared in the current scope, not imported from a module, or misspelled—it emits error TS2304. This error commonly appears in three scenarios: 1. **Undefined variables or functions**: You're using a name that was never declared 2. **Missing imports**: You're referencing something from another file but haven't imported it 3. **Missing type definitions**: Third-party libraries lack corresponding TypeScript declarations The error is one of the most common TypeScript issues because it requires careful attention to scope, imports, and naming conventions. Case sensitivity is also important—TypeScript distinguishes between `myVar` and `MyVar`.
Typical symptoms
- Red squiggly line in your IDE (VS Code, WebStorm) under an identifier
- TypeScript compilation fails immediately with error TS2304
- Error message: 'Cannot find name' followed by the undefined identifier name
- Code works in JavaScript but breaks when you switch to TypeScript
- Errors appear for imported types or classes from installed packages
- The identifier exists in your code but TypeScript still can't find it
Common causes
- Variable, function, or type is used before it's declared (order matters)
- You forgot to import a name from another file or module
- You misspelled the identifier (including wrong case: myVar vs MyVar)
- The identifier is scoped incorrectly (defined in a function but used outside)
- Missing type definitions for third-party packages (@types packages)
- Incorrect tsconfig.json configuration (missing include paths, wrong lib settings)
- The module/file you're trying to import from doesn't export that name
- Using a global variable without proper declaration (e.g., require without @types/node)
How to fix "Cannot find name 'X'"
First, verify that the name you're using is actually declared in your code. Look for a line like:
const myVar = "hello";
const myFunction = () => {};
type MyType = { name: string };If the name doesn't exist anywhere, you need to declare it. For example:
// BEFORE: Error - name not defined
console.log(myVar);
// AFTER: Define it first
const myVar = "hello";
console.log(myVar);If the identifier is defined in another file, you must import it before using it:
// In file: utils.ts
export const formatDate = (date: Date) => {
return date.toLocaleDateString();
};
// In file: main.ts - BEFORE: Error TS2304 - cannot find name 'formatDate'
const result = formatDate(new Date());
// In file: main.ts - AFTER: Import it first
import { formatDate } from "./utils";
const result = formatDate(new Date());Common import patterns:
// Named import
import { ComponentName } from "./components";
// Default import
import MyLibrary from "my-library";
// Type import (TypeScript 3.8+)
import type { MyType } from "./types";TypeScript is case-sensitive. Verify that your identifier matches exactly:
// WRONG - case mismatch
const myVariable = "test";
console.log(myvariable); // Error: cannot find name 'myvariable'
// CORRECT
console.log(myVariable);Common typo patterns:
// Missing camelCase
const firstName = "John"; // wrong: firstname, FirstName
const getUserData = () => {}; // wrong: getuserdata, GetUserData
// Miscounted underscores or wrong separators
const _privateVar = 5; // wrong: privateVar, private_var
const kebab_case = ""; // wrong: kebabCase (should use camelCase in JS/TS)Use your IDE's "Find and Replace" feature (Ctrl+H / Cmd+H) to search for typos.
If you're using a third-party library and getting "Cannot find name" errors for its exports, you likely need type definitions:
# Example: using lodash
npm install lodash
# Get types for lodash
npm install --save-dev @types/lodash
# Example: using node utilities like 'require'
npm install --save-dev @types/nodeThen import and use as normal:
// After npm install --save-dev @types/node
const path = require("path"); // Now recognized without error
// or
import * as path from "path";Find type packages at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped).
If TypeScript can't find global types or is misconfigured, update your tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM"],
"typeRoots": ["./node_modules/@types"],
"types": ["node"]
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}Common fixes:
- Missing "lib" entry: Add "DOM" if using browser APIs (window, document)
- Missing "typeRoots": Ensures TypeScript finds @types packages
- Incorrect include/exclude: Make sure your source files are included
- Missing @types in types array: Explicitly include node if using Node.js APIs
For legitimate global variables (rare), declare them using declare:
// In a .d.ts file or at top of a .ts file
declare const API_KEY: string;
declare function externalFunction(): void;
declare type GlobalType = { id: number };
// Now you can use them
console.log(API_KEY);
externalFunction();
const obj: GlobalType = { id: 1 };Best practice is to avoid globals when possible—use imports instead. This pattern is mainly for legacy code or external scripts.
Advanced notes
### Scope and Hoisting
JavaScript/TypeScript has function scope and block scope. Variables declared with let and const are block-scoped:
if (true) {
const blockScoped = "here";
}
console.log(blockScoped); // Error: Cannot find name
// Correct: declare outside
const blockScoped = "here";
if (true) {
console.log(blockScoped); // OK
}### React/JSX Special Cases
In React with TypeScript, ensure you have proper imports:
// WRONG in React with TypeScript
function MyComponent() {
return <div>Hello</div>; // May error if React not imported
}
// CORRECT (depending on React version)
// React 17+: JSX transform (no import needed)
// React <17: Must import React
import React from "react";
import type { FC } from "react";
const MyComponent: FC = () => {
return <div>Hello</div>;
};Update tsconfig.json for JSX:
{
"compilerOptions": {
"jsx": "react-jsx",
"lib": ["ES2020", "DOM"]
}
}### Module Resolution
If imports aren't resolving, check your tsconfig.json module resolution strategy:
{
"compilerOptions": {
"moduleResolution": "node",
"baseUrl": "./src",
"paths": {
"@/*": ["./*"]
}
}
}This allows imports like import { utils } from "@/utils";
### CommonJS vs ES Modules
Mixing CommonJS and ES modules can cause issues:
// CommonJS (Node.js style) - not fully typed by default
const myModule = require("my-module");
// ES Modules (modern, recommended)
import myModule from "my-module";For Node.js CommonJS, install @types/node and ensure tsconfig includes it.
Frequently asked questions
- What does "TS2304" mean?
- TypeScript is a statically-typed language that requires all identifiers to be declared before they can be used. When the TypeScript compiler encounters a name that it cannot resolve—either because it's not declared in the current scope, not imported from a module, or misspelled—it emits error TS2304. This error commonly appears in three scenarios: 1.
- How do I fix "TS2304"?
- This TypeScript compiler error occurs when you reference a variable, type, class, or function that hasn't been declared or imported. The fix involves declaring the name, importing it from another module, or fixing typos.
- What causes "TS2304"?
- Variable, function, or type is used before it's declared (order matters) You forgot to import a name from another file or module You misspelled the identifier (including wrong case: myVar vs MyVar)
- Is the "TS2304" error serious?
- Yes. This is a high-severity error that usually blocks work until it is fixed, but the steps above resolve it.
Official resources & further reading
- 📚TypeScript Official Documentation
- 📖TypeScript Handbook - Basic Types(Official Docs)
- 📖TypeScript Handbook - Modules(Official Docs)
- 📖TypeScript TSConfig Reference(Official Docs)
- 🐙