在TS中Sequelize的Model和Instance应该怎么声明? - CNode技术社区

在TS中Sequelize的Model和Instance应该怎么声明?
发布于 8 年前 作者 liuzhiguo11 4750 次浏览 来自 问答
// model/user.ts
import {Application} from "egg";
export default (app: Application) => {
 const {STRING} = app.Sequelize
 const user = app.model.define('user', {
 account: STRING(50),
 password: STRING(50),
 userName: {
 type: STRING,
 field: 'user_name',
 },
 displayPhoto: {
 type: STRING,
 field: 'display_photo'
 },
 accessToken: {
 type: STRING,
 field: 'access_token',
 }
 })
 user.associate = function () {
 const {User, Auth, Role, UserRole} = app.model
 User.hasMany(Auth)
 User.belongsToMany(Role, {through: {model: UserRole}})
 }
 return user
}
//index.d.ts
declare interface UserModel extends BaseModel {
 account: string,
 password: string,
 userName: string,
 displayName: string,
 accessToken: string
}
declare module 'egg' {
 interface Application {
 Sequelize: SequelizeStatic
 model: Sequelize & Context["model"]
 }
 interface Context {
 model: {
 Menu: Model<MenuModel, any>
 Role: Model<RoleModel, any>
 RoleMenu: Model<RoleMenuModel, any>
 User: Model<UserModel, any>
 Auth: Model<AuthModel, any>
 UserRole: Model<UserRoleModel, any>
 }
 }
}

这样写大部分功能都是能通的,但我现在希望调用实例的get({plain:true})的方法,webstorm就会报错 QQ图片20180331133559.png

//实现这样一个service方法
async getMenuTree(){
	const all_menu=await model.Menu.findAll()
	all_menu.forEach(item=>{
		item.get({plain:true}) //报错
		//发现调用model.Menu.create() model.Menu.update()得到的数据都不能调用.get()方法。		
	})	
}

上面的item和model.Menu.create()返回的类型应该是Instance吧,如何让findAll,create等返回Instance?对泛型数据云里雾里的

3 回复

上面的图是原js代码

来自酷炫的 CNodeMD

解决了,这感觉完全就是教编辑器如何代码提示嘛,都是手动档的话真心啰嗦的一B QQ图片20180331170123.png QQ图片20180331170130.png QQ图片20180331170252.png

不想用这种方式,可以试试egg-di,使用依赖注入的当时,自己import。

回到顶部

AltStyle によって変換されたページ (->オリジナル) /