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

TypeScript新手求助:自定义JS函数声明文件报错无智能提示

Fixing Your Custom JavaScript Declaration File Issue

Hey there! Let's get that TypeScript declaration file working properly for your main.js module. The errors you're seeing come from two key mismatches: the module name in your declaration file doesn't match your import path, and the declared structure doesn't align with what your JS code actually exports.

1. Fix the Module Path in Your Declaration File

Your index.ts imports from "./main" (a relative path), but your type.d.ts declares a module named "main" (without the ./). TypeScript needs these to match exactly. Update your type.d.ts to target the correct relative path:

declare module './main' {
  // We'll define the correct structure here next
}

2. Match the Declared Structure to Your JS Export

Your main.js exports an object (maths) that contains a sum method. Your original declaration tried to export a standalone sum function, which doesn't match. Let's fix that to reflect the actual structure:

declare module './main' {
  // Define the shape of the exported object
  interface MathsModule {
    sum(a: number, b: number): void;
  }

  // Export the object that matches this interface
  const maths: MathsModule;
  export = maths;
}

If you prefer a more concise version (that still works with your import pattern), you can write:

declare module './main' {
  export const sum: (a: number, b: number) => void;
}

3. Ensure TypeScript Recognizes Your Declaration File

Double-check your tsconfig.json to make sure it includes your type.d.ts file. Add it to the include array if it's not already there:

{
  "compilerOptions": {
    "module": "commonjs", // Matches your CommonJS-style export in main.js
    "target": "es5",
    "strict": true,
    "esModuleInterop": true // Smooths out CommonJS/ES module interop
  },
  "include": [
    "index.ts",
    "type.d.ts"
  ]
}

4. Test the Fixed Code

Now your index.ts should work with full IntelliSense:

import * as mt from "./main";
mt.sum(2, 5); // TypeScript will recognize sum and validate number arguments

That should resolve the "Could not find a declaration file" error and give you the IntelliSense you're looking for!

内容的提问来源于stack exchange,提问作者Chnkz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:08:33