如何解决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
相关产品推荐
相关产品推荐

