“找不到模块的声明文件”,typeRoots 文件夹中的自定义声明文件被忽略

sry*_*cad 5 javascript node.js typescript tsc tsconfig

您好,我遇到了 TypeScript 问题。我有以下目录结构:

  • package.json:顶级项目
  • node_modules/:所有已安装的库
  • tsconfig.json
  • build/:生成的文件夹
    • 索引.js
    • 处理程序.js
    • ...
  • server/: a folder with a TypeScript server built on top of the build folder
    • typings/
      • handler/
        • index.d.ts
    • tsconfig.json:
    • index.ts: a TypeScript server

The file server/tsconfig.json contains the lines

    "compilerOptions": {
        "typeRoots": [
            "../node_modules/@types",
            "./typings"
        ],
    ...
    "include": [
        "./*.ts",
        "./typings/**/*.ts"
    ],
Run Code Online (Sandbox Code Playgroud)

I import an un-typed JavaScript function in TypeScript in the file server/index.ts:

import { handler } from '../build/handler.js'
... (code using handler) ...
Run Code Online (Sandbox Code Playgroud)

The file server/typings/handler/index.d.ts contains

declare module 'handler' {
    export const handler: (a: any) => void 
}
Run Code Online (Sandbox Code Playgroud)

But this declaration file is not picked up by tsc. Running npx tsc --project server/tsconfig.json" gives

server/index.ts(6,25): error TS7016: Could not find a declaration file for module '../build/handler.js'. '/home/..../build/handler.js' implicitly has an 'any' type.
Run Code Online (Sandbox Code Playgroud)

Adding --traceResolution shows that the build/handler.d.ts file location is checked, but the typings/handler/index.d.ts location is not checked.

I have read Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type but this does not mention a relative import.

I tried Could not find declaration file with custom declaration file for 'react-dates' module but it doesn't help.

How can I make TypeScript detect the handler.d.ts file in the typeRoots directory?