[eggjs/egg]eggjs-ts 使用egg-sequelize的datasources 抛出:Property 'appOneModel' does not exist on type 'Application'.

2025-11-04 591 views
3
What happens?

eggjs-ts 使用egg-sequelize的datasources 抛出:Property 'appOneModel' does not exist on type 'Application'. 查询了相关问题但是没有结局。目前是静态类检查出现错误,所以请教一下。我看egg-sequelize已经有index.d.ts,也没有相关的讨论,所以上来请教下

Mini Showcase Repository(REQUIRED)

https://github.com/smallos/eggjs-ts-sequelize

启动npm run dev 会出现

/Users/nico/Documents/work/Learn/eggjs/node_modules/ts-node/src/index.ts:261 return new TSError(diagnosticText, diagnosticCodes) ^ TSError: [egg-core] load file: /Users/nico/Documents/work/Learn/eggjs/app/model/app_one/one.ts, error: ⨯ Unable to compile TypeScript: app/model/app_one/one.ts(6,19): error TS2339: Property 'appOneModel' does not exist on type 'Application'.

How To Reproduce

Steps to reproduce the behavior: 1.npm i 2.npm run dev

Expected behavior 1.正常可以启动

Context Node Version:v12.1.0 Egg Version:egg@2.26.0 Plugin Name:egg-sequelize Plugin Version:egg-sequelize@5.2.1 Platform:mac

回答

8

参考 https://github.com/eggjs/examples/tree/master/sequelize-ts

3

参考 https://github.com/eggjs/examples/tree/master/sequelize-ts

这个我看过,一个的时候是可以的。但是使用datasources,两个库的时候出现的异常

5

datasources 的话,需要用 as

7

可以给一个例子吗?这个是自己学习ts的项目,不是很清楚具体怎么实施

6

那你需要先对着 ts 官方文档系统学习一下,不要一下子步子跨的太大

2

目前的实践是 const two = (app as any).appOneModel.define('two', { id: { type: INTEGER, primaryKey: true, autoIncrement: true}, created_at: DATE, updated_at: DATE, }, { freezeTableName: true, }); 但不清楚是不是最佳实践

0

两种方式

((app as any).dbRegion as IModel).define。(IModel 要从egg中引入)

在typings/model/ 新增一个 sequelize.d.ts, 添加:


declare module 'egg' {

interface Application {
appOneModel: IModel;
}

}

1

因为在实际的开发中,typings目录一般都是ignore了的,所以感觉将d.ts放到这个目录不是很恰当,我的做法是在app目录下新建了declare.ts的文件,用来放一些需要声明的定义:

import 'egg';
import ExportResetRecord from './reset_model/ResetRecord';

declare module 'egg' {
    interface IResetModel extends IModel {
        ResetRecord: ReturnType<typeof ExportResetRecord>;
    }

    interface Application {
        securityModel: IResetModel;
    }
}

IResetModel需要继承IModel,这样才能获取到IModel相关的声明