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

为何ts-node无法识别自定义类型声明文件,而tsc与Webstorm可正常识别?

Why ts-node Can't Recognize Your Custom Type Declaration (But tsc & WebStorm Can)

Great question—this is a common gotcha when working with ts-node in ESM mode. Let’s break down why this happens and how to fix it.

Why the Discrepancy?

First, let’s clarify why tsc and WebStorm work fine while ts-node throws an error:

  • tsc: Strictly follows your tsconfig.json rules. Your include: ["./src/**/*"] wildcard correctly picks up src/types/custom.d.ts, and typeRoots tells it to look in that directory for custom types.
  • WebStorm: Its built-in TypeScript service scans all .d.ts files in your project (unless explicitly excluded), so it automatically finds your declaration regardless of minor config quirks.
  • ts-node (ESM mode): When running with ES modules enabled (via "ts-node": { "esm": true } and --experimental-specifier-resolution=node), ts-node’s type resolution logic has subtle differences from tsc. It may not automatically load all included .d.ts files by default, or might prioritize different lookup paths.

Fixes to Try (Ordered by Simplicity)

1. Add the --files Flag to Your ts-node Command

ts-node doesn’t load all included files by default in ESM mode. Adding the --files flag forces it to process every file specified in your include array, including your custom type declaration:

NODE_OPTIONS='--experimental-specifier-resolution=node' npx ts-node --files -P tsconfig.json src/index.ts

2. Explicitly Include Your custom.d.ts in tsconfig.json

While ./src/**/* should match your type file, sometimes ts-node’s ESM parser doesn’t resolve the wildcard as expected. Try adding the file path directly to your include array:

{
  "include": [ "./src/**/*", "./src/types/custom.d.ts", "jest.config.js" ]
}

3. Restructure Your Type Declarations to Match @types Convention

ts-node tends to prioritize the standard @types directory structure. Create a src/@types/mongo-uri-tool/index.d.ts file with your declaration:

declare module 'mongo-uri-tool';

Since your typeRoots includes src/types, renaming the directory to @types (under src) aligns with TypeScript’s default type lookup behavior, which ts-node handles more reliably.

4. Update ts-node to the Latest Version

Older versions of ts-node had bugs in ESM type resolution. Run this to upgrade:

npm install --save-dev ts-node@latest

Verify the Fix

After trying any of these solutions, re-run your ts-node command— the TS7016 error should disappear, and ts-node will recognize your custom module declaration just like tsc and WebStorm do.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:57:28