You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the Transaction interface into the scope of your moduleB declaration.
  • Transaction is 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 20:32:51