TypeScript报错:子类方法与基类接口类型不兼容问题排查
移除await后触发TypeScript类型错误的原因解析
相关代码定义
参数类型定义
export type RemoveGroupRecipientParams = { id: number; removeUserId: number; issuerId: number; };
实现方法
async removeGroupRecipient(params: RemoveGroupRecipientParams) { const { issuerId, removeUserId, id } = params; const userToBeRemoved = await this.userService.findUser({ id: removeUserId, }); if (!userToBeRemoved) throw new HttpException('User cannot be removed', HttpStatus.BAD_REQUEST); const group = await this.groupService.findGroupById(id); if (!group) throw new GroupNotFoundException(); if (group.creator.id !== issuerId) throw new NotGroupOwnerException(); if (group.creator.id === removeUserId) throw new HttpException( 'Cannot remove yourself as owner', HttpStatus.BAD_REQUEST, ); group.users = group.users.filter((u) => u.id !== removeUserId); const savedGroup = await this.groupService.saveGroup(group); return { group: savedGroup, user: userToBeRemoved }; }
问题场景
当移除const savedGroup = await this.groupService.saveGroup(group);中的await关键字后,触发如下TypeScript错误:
error TS2416: Property 'removeGroupRecipient' in type 'GroupRecipientService' is not assignable to the same property in base type 'IGroupRecipientService'. Type '(params: RemoveGroupRecipientParams) => Promise<{ group: Promise<Group>; user: User; }>' is not assignable to type '(params: RemoveGroupRecipientParams) => Promise<RemoveGroupUserResponse>'. Type 'Promise<{ group: Promise<Group>; user: User; }>' is not assignable to type 'Promise<RemoveGroupUserResponse>'. Type '{ group: Promise<Group>; user: User; }' is not assignable to type 'RemoveGroupUserResponse'. Types of property 'group' are incompatible. Type 'Promise<Group>' is missing the following properties from type 'Group': id, users, creator, messages, and 3 more. 43 async removeGroupRecipient(params: RemoveGroupRecipientParams) {
基类接口定义
export interface IGroupRecipientService { addGroupRecipient( params: AddGroupRecipientParams, ): Promise<AddGroupUserResponse>; removeGroupRecipient( params: RemoveGroupRecipientParams, ): Promise<RemoveGroupUserResponse>; }
疑问
RemoveGroupRecipientParams中并未包含Promise类型,为何移除await后会触发该类型不兼容错误?
原因分析
这个错误和RemoveGroupRecipientParams的类型完全无关,问题出在返回值的类型不匹配上:
this.groupService.saveGroup(group)本身是异步方法,返回的是Promise<Group>类型的结果。- 保留
await时,savedGroup会被自动解析为Group实例,此时返回的{ group: savedGroup, user: userToBeRemoved }完全符合RemoveGroupUserResponse的结构(该类型要求group字段是实际的Group实例)。 - 移除
await后,savedGroup的类型变成了Promise<Group>,这时候返回的对象里group字段是一个未解析的Promise,而不是Group实例。但接口IGroupRecipientService要求removeGroupRecipient返回的Promise<RemoveGroupUserResponse>中,包裹的对象的group必须是Group类型,而非Promise,因此TypeScript检测到类型不兼容,抛出错误。
内容的提问来源于stack exchange,提问作者MD Jahid Hasan
相关产品推荐
相关产品推荐

