使用Create React App的TypeScript项目对接JS库的类型声明问题
Let's fix your issue step by step. The problem stems from how TypeScript handles global type declarations in a module-based project like CRA TypeScript, so here's the correct approach:
Correct Global Type Declaration
Create a proper global type file
First, make aarea.d.tsfile inside yoursrc/typesdirectory (create thetypesfolder if it doesn't exist). This location works perfectly because Create React App's default TypeScript config automatically includes all files undersrc/for type checking.Paste this code into the file:
declare global { namespace Area.Subcategory { function fn(): void; } } export {}; // This line is critical: it converts the file into a module, which allows `declare global` to function correctlyCall the library without extra imports
Now you can directly use the library in yourApp.tsx—no reference comments or imports needed:import React from "react"; export interface IAppProps {} export default class App extends React.Component<IAppProps, any> { public componentDidMount() { Area.Subcategory.fn(); // TypeScript will recognize this now } public render() { return <div className="App">(placeholder)</div>; } }
Why Your Previous Attempts Failed
First attempt (plain namespace without
declare global):
If your.d.tsfile had noimport/exportstatements, TypeScript treats it as a global script file. But in CRA's module-focused setup, this standalone global declaration might not be picked up correctly. Wrapping the namespace indeclare globalinside a module (viaexport {}) ensures it merges properly into the global scope.Second attempt (wrapping in a module):
Declaringmodule "test"tells TypeScript you're defining types for a module imported viaimport * as test from "test", but your actual library is a global variable—not a module. That's why you got the "Module not found" error: there's no real module file namedtestin your project.Reference comments and typings folder:
CRA's TS config already includes all files undersrc/, so moving the file to atypingsfolder would require extratsconfig.jsonsetup (like adding"typings/**/*"to theincludearray). The///<reference path="..." />directive is often unnecessary in modern TS setups and can break if file paths change.
Verify the Declaration Works
To confirm TypeScript is recognizing your type file, intentionally add a syntax error (e.g., rename fn to fnWrong in the .d.ts file). You should see a TypeScript error in App.tsx when calling Area.Subcategory.fn(), which proves the declaration is active.
内容的提问来源于stack exchange,提问作者bcnoexceptions

