NestJS 神奇导入 - Nest 无法解析依赖项

问题描述 投票:0回答:1

所以我正在学习本教程https://www.tomray.dev/nestjs-nextjs-trpc

完成 NestJS 部分后发现我的代码无法正常工作并抛出此错误,而我的代码看起来与教程中的代码相同。

[Nest] 94625  - 10/01/2024, 11:43:53 AM   ERROR [ExceptionHandler] Nest can't resolve dependencies of the TrpcRouter (?). Please make sure that the argument Function at index [0] is available in the TrpcModule context.

Potential solutions:
- Is TrpcModule a valid NestJS module?
- If Function is a provider, is it part of the current TrpcModule?
- If Function is exported from a separate @Module, is that module imported within TrpcModule?
  @Module({
    imports: [ /* the Module containing Function */ ]
  })

这是该模块的代码:

import { Injectable, type INestApplication } from '@nestjs/common';
import type { TrpcService } from './trpc.service';
import { z } from 'zod';
import * as trpcExpress from '@trpc/server/adapters/express';

@Injectable()
export class TrpcRouter {
  constructor(private readonly trpc: TrpcService) {}

  appRouter = this.trpc.router({
    hello: this.trpc.procedure
      .input(z.object({ name: z.string().optional() }))
      .query(({ input }) => {
        return `Hello ${input.name ? input.name : 'World'}!`;
      }),
  });

  async applyMiddleware(app: INestApplication) {
    app.use(
      '/trpc',
      trpcExpress.createExpressMiddleware({ router: this.appRouter }),
    );
  }
}

export type AppRouter = TrpcRouter['appRouter'];

尝试不同的方法后,我发现导致此错误的原因是我正在导入类型,而不是这一行的整个模块

import type { TrpcService } from './trpc.service';

更改为原始教程版本后

import { TrpcService } from './trpc.service';

它开始正常工作。

但我仅将其用作类型,而不是值

  constructor(private readonly trpc: TrpcService) {}

所以问题是——为什么会发生这种情况?为什么当我只导入类型而不导入值时它会抛出错误?我想这就是 NestJS 的工作原理,还是我在打字稿处理它的方式中遗漏了一些东西?

PS:还有其他与此类似的问题,但没有一个讨论这种特殊差异 - 类型导入/常规导入

PPS:搜索类型导入时我发现了这个问题,这可能是我问题的答案。现在阅读https://github.com/nestjs/nest/issues/5421

typescript nestjs
1个回答
0
投票

所以,是的,这就是 NestJS 的工作原理,它无法修复,应该予以考虑:

https://github.com/nestjs/nest/issues/5421#issuecomment-692295353

依赖注入在使用node期间运行,而不是在tsc使用期间运行。这 意味着构建阶段发生的事情只是 将 Typescript 转译为 JavaScript,在此期间,键入 检查导入的类型是否正确,然后变成 {} 就像 接口。这不是 Nest 能够解决的问题, 而是在过程中应该考虑的事情 发展。如果您想使用类接口或注入令牌 对于自定义提供商,这是可以管理的,但是 Nest 的 DI 系统无法绕过 Typescript 的导入功能 类型。

© www.soinside.com 2019 - 2024. All rights reserved.