Sequelize+TypeScript报错TS2339:Todo类不存在findAll属性
Sequelize TypeScript 类型错误:
findAll 属性不存在于 typeof Todo 错误信息
TSError: ⨯ Unable to compile TypeScript:
controller/todo.controller.ts:7:46 - error TS2339: Property 'findAll' does not exist on type 'typeof Todo'.const todos: Promise = await Todo.findAll()
相关代码
模型定义(Todo.ts)
class Todo extends Model<InferAttributes<Todo>, InferCreationAttributes<Todo>>{ declare id: CreationOptional<number>; declare todo: string; declare status: string; } Todo.init({ id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, // other fields }, { sequelize, tableName: 'todos', }); export default Todo
控制器代码(todo.controller.ts)
export const getAllTodos = async (req: Request, res: Response) => { try { const todos = await Todo.findAll() } catch (e) { console.log(e); } };
已按配置指南完成Sequelize + TypeScript环境搭建,数据库连接正常,但仍触发上述类型错误。
解决方法
1. 校验导入的正确性
确保模型文件中从Sequelize完整导入所需类型与类:
import { Model, InferAttributes, InferCreationAttributes, CreationOptional, DataTypes } from 'sequelize'; import sequelize from './path-to-your-sequelize-instance'; // 替换为实际的实例路径
2. 显式声明静态方法类型
给Todo类添加静态方法的类型声明,让TypeScript识别Sequelize内置的静态方法:
class Todo extends Model<InferAttributes<Todo>, InferCreationAttributes<Todo>>{ declare id: CreationOptional<number>; declare todo: string; declare status: string; // 声明常用静态方法的类型 declare static findAll: typeof Model.findAll; declare static findByPk: typeof Model.findByPk; declare static create: typeof Model.create; }
3. 检查版本兼容性
确保Sequelize(v6+)与TypeScript(4.1+)版本匹配,版本不兼容会导致类型推导失效。可执行命令更新:
npm update sequelize typescript
4. 改用ModelDefined类型定义模型
通过ModelDefined明确指定模型的属性与创建属性类型,避免类型推导问题:
import { ModelDefined, DataTypes } from 'sequelize'; // 定义模型属性 interface TodoAttributes { id: number; todo: string; status: string; } // 定义创建时的属性(省略自动生成的id) interface TodoCreationAttributes extends Omit<TodoAttributes, 'id'> {} const Todo: ModelDefined<TodoAttributes, TodoCreationAttributes> = sequelize.define('Todo', { id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true }, todo: { type: DataTypes.STRING, allowNull: false }, status: { type: DataTypes.STRING, defaultValue: 'pending' } }, { tableName: 'todos' }); export default Todo;
内容的提问来源于stack exchange,提问作者Nikita Gorshkov
相关产品推荐
相关产品推荐

