[eggjs/egg]extend/helper.ts 在函数中使用 this.app 操作

2024-08-05 131 views
9
What happens?

使用 ts 时,在extend/helper.ts的定义一个函数,函数中使用 this.app,会报错说 this 上不存在 app 属性,请问如何进行 ts 类型定义?

image

相关环境信息
  • 操作系统:macOS 10.14.2
  • Node 版本:10.14.0
  • Egg 版本:2.26.0

回答

8

TS 基础知识。

export default {
  getConfigFileName(this: Context, env) {
  },
}
5

确实是 TS 知识,献丑了,已解决

6

helper 的 this 是 Context,不是 Application,刚才写错了。

6

this 的类型可以定义为 IHelper 吗

3

你打印看看,我记不清了,应该是 IHelper

2

好的

1

@atian25 Hi,为什么不考虑把 Helper 也像 Controller Service 一样封装,通过自定义继承让我能直接拿到 this 呢?

1

helper 没必要那么复杂吧,它的定位就是给模板渲染用的。

如果你需要的话,自己通过 app.loader.loadToContext 来加载自定义的 app/utils 目录到 app.utils 这样,自定义规则

5

@atian25 模板渲染···怪不得用起来感觉怪怪的··我这边之间写个 HelperService 来把一些常用的逻辑放在里面,这样可以用到 Context。应该符合你们的设计初衷吧。

6

@atian25 谢谢!