Egg: ts 模式下,egg-mongoose 创建的 model 不能在 ctx.model 下成功获取到代码提示

Created on 12 Jul 2018  ·  11Comments  ·  Source: eggjs/egg

示例

按照官方文档 npx egg-init --type=ts showcase 创建的项目,引入 egg-mongoose的文档示例,在 Controller 下使用 ctx.model 不能够获取到对应的 User model 的提示,typeings/app/model/index.d.ts 有成功创建,参考如图:
image

Most helpful comment

@vagusX 应该需要配置一个文件的好像, cc @whxaxes

https://github.com/eggjs/egg/issues/3480 完成后,应该就不需要配置就可以自动分析插件的

All 11 comments

Translation of this issue:


ts mode, model created by egg-mongoose can not successfully get code hints under ctx.model

[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:
image

egg-mongooseindex.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 感谢两位的解答,在此之前我都是手动书写每个 modelinterface 的~

@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

Was this page helpful?
0 / 5 - 0 ratings