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

如何解决Angular路由模块导入懒加载模块的ESLint类型定义错误?

解决Angular懒加载路由ESLint类型注解错误的方法

下面是几种不用忽略ESLint规则的解决方式:

  • 显式指定返回类型
    从@angular/core导入Type,给loadChildren的箭头函数加上Promise<Type<any>>的返回类型标注:

    import { Type } from '@angular/core';
    // ...
    {
      path: 'user',
      children: [
        {
          path: ':id',
          loadChildren: (): Promise<Type<any>> =>
            import('./user/user.module').then(m => m.UserModule),
        },
      ],
    }
    
  • 使用Angular内置的LoadChildrenCallback类型
    从@angular/router导入专门的LoadChildrenCallback类型,两种写法可选:
    直接标注写法:

    import { LoadChildrenCallback } from '@angular/router';
    // ...
    {
      path: 'user',
      children: [
        {
          path: ':id',
          loadChildren: ((): LoadChildrenCallback => 
            import('./user/user.module').then(m => m.UserModule))(),
        },
      ],
    }
    

    变量引用写法(可读性更强):

    import { LoadChildrenCallback } from '@angular/router';
    
    const userLoadChildren: LoadChildrenCallback = () =>
      import('./user/user.module').then(m => m.UserModule);
    
    // 路由配置
    {
      path: 'user',
      children: [
        {
          path: ':id',
          loadChildren: userLoadChildren,
        },
      ],
    }
    
  • 给回调参数加类型注解
    如果ESLint提示的是then回调里的m缺少类型,直接给m加上模块的类型:

    {
      path: 'user',
      children: [
        {
          path: ':id',
          loadChildren: () =>
            import('./user/user.module').then(
              (m: typeof import('./user/user.module')) => m.UserModule
            ),
        },
      ],
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:05:29