TypeScript跨文件引用类型定义报错:无法找到Transaction类型?
Why
Transaction Can't Be Found Even With a Reference Path? The Core Issue: Module Scope Isolation
That error happens because TypeScript's module system keeps each module's members isolated by default:
- The
///<reference path="../moduleA/moduleA.d.ts" />line only tells TypeScript "hey, this file exists" — it doesn't pull theTransactioninterface into the scope of yourmoduleBdeclaration. Transactionis an exported member of the'moduleA'module, so you can't access it directly in another module without explicitly importing it.
Fix: Explicitly Import the Type
You need to add an import statement inside the moduleB declaration to bring in Transaction from moduleA. Here's the corrected code:
///<reference path="../moduleA/moduleA.d.ts" /> declare module 'moduleB' { // Import the Transaction type from moduleA import { Transaction } from 'moduleA'; export class MyClass { constructor(private transaction: Transaction) {} } }
If you're using TypeScript 3.8 or later, you can use import type for clearer type-only imports (this is a best practice for type declarations):
///<reference path="../moduleA/moduleA.d.ts" /> declare module 'moduleB' { import type { Transaction } from 'moduleA'; export class MyClass { constructor(private transaction: Transaction) {} } }
Bonus Tip
If your tsconfig.json includes the ./src/@types directory in typeRoots or include, you can actually omit the ///<reference path="..." /> line entirely — TypeScript will automatically find and load your type definition files.
内容的提问来源于stack exchange,提问作者o..o
相关产品推荐
相关产品推荐

