如何从 TypeScript 中的其他服务动态访问方法?

gachiKoKa

我刚开始学习ts。我从控制器中的请求中获取类型名称。例如,它可能是“follow”或“check_follow”。我想从 follow_service.ts 类动态访问适当的方法。我怎样才能做到这一点?目前我正在尝试这样做:

this.followService[req.body.opeationType](author_id, fan_id);

但是打字稿对我大喊大叫:

TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'PaymentService'.

我该怎么办?谢谢!

跟随服务看起来像:

class FollowService {

public async follow(author_id: string, fan_id: string): Promise<any> {
    ///
  }
public async follow(author_id: string, fan_id: string): Promise<any> {
    ///
  }
}
乙肝

如果您的服务有一个类型,您会断言该请求为您提供了一个密钥(当然,您可能应该确保实际情况也是如此):

this.followService[req.body.opeationType as keyof FollowService](author_id, fan_id);

目前假设所有内容FollowService都是一个具有接受两个 ID 的兼容签名的函数。

解决这些问题的最简单方法是手动列出有效密钥:

this.followService[req.body.opeationType as 'follow' | 'check_follow'](author_id, fan_id);

使用高级类型,您还可以'follow' | 'check_follow'动态创建结果类型

type FollowServiceFunctions = {
    [K in keyof FollowService]: FollowService[K] extends
        (author_id: string, fan_id: string) => Promise<any> ? K : never
}[keyof FollowService]

// ...

this.followService[req.body.opeationType as FollowServiceFunctions](author_id, fan_id);

服务的类型声明通常看起来与您在问题中列出的非常相似:

declare class FollowService {
    follow(author_id: string, fan_id: string): Promise<any>;
    check_follow(author_id: string, fan_id: string): Promise<any>;
}

但是根据服务的提供方式,例如通过全局变量、本机模块、CommonJS 模块等,细节可能会有所不同。参阅文档,因为这可能很棘手,并且是处理 TypeScript 问题的主要部分。建议对这些声明的工作方式有一个很好的理解。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章