Translation of this issue:
[Example] (https://github.com/gu-xionghong/egg-example)
According to the project created by the official document npx egg-init --type=ts showcase, introduce the document example of egg-mongoose, and use ctx.model under Controller to get the corresponding User model. The prompt, typeings/app/model/index.d.ts has been successfully created, refer to the figure:

egg-mongoose 的 index.d.ts 是我加上去的,但是有个失误,我提了个新 PR #24,合并之后你重新安装一下依赖应该就可以了。
但是支持程度只是说你写出 ctx.model.User 之后,能知道 User 是一个 mongoose.Model。
关于联想出 ctx.model 下面有哪些 model,需要 egg-ts-helper 支持,目前应该是只支持 sequelize,没支持 mongoose 的,需要 PR。
@BaffinLee 谢谢解答
@gu-xionghong 借助 egg-ts-helper 自动生成的 typings/app/model 目录下 *.d.ts, 其中包含一个 egg scope 下的 IModel,在 typings 下, 新建一个 index.d.ts, 自行覆盖
import * as mongoose from 'mongoose';
declare module 'egg' {
// extend app
interface Application {
model: IModel;
}
// extend context
interface Context {
model: IModel;
}
}
这样就会有 this.ctx.model 下的提示了
@vagusX 应该需要配置一个文件的好像, cc @whxaxes
https://github.com/eggjs/egg/issues/3480 完成后,应该就不需要配置就可以自动分析插件的
@atian25 @gu-xionghong 确实 egg-ts-helper 通过配置下即可完成
// tshelper.js
module.exports = {
watchDirs: {
model: {
path: 'app/model',
generator: 'function',
interface: 'IModel',
declareTo: 'Context.model',
// interfaceHandle: val => `ReturnType<typeof ${val}>`, 这一行不需要
}
}
}
@vagusX @atian25 感谢两位的解答,在此之前我都是手动书写每个 model 的 interface 的~
@vagusX
module.exports = {
watchDirs: {
model: {
path: 'app/model',
generator: 'function',
interface: 'IModel',
declareTo: 'Context.model',
}
}
}
function 这个 generator 就是 ReturnType<typeof ${val}> 的,可以去掉
@whxaxes 你说的这种我之前试了 不加
interfaceHandle: val => `ReturnType<typeof ${val}>`,
的话,只有 this.ctx.model 的提示,this.ctx.model.User.create 就 any 了...
@vagusX function 的 generator 就是给 interfaceHandle 一个默认值,就是 ReturnType<typeof ${val}> ,https://github.com/whxaxes/egg-ts-helper/blob/master/src/generators/function.ts#L5
@whxaxes 你说的是对的 我又试了一下 确实是不需要写 interfaceHandle
Most helpful comment
@vagusX 应该需要配置一个文件的好像, cc @whxaxes
https://github.com/eggjs/egg/issues/3480 完成后,应该就不需要配置就可以自动分析插件的