跳至主要内容
版本:v6 - 稳定版

TypeScript

信息

我们正在努力使 Sequelize 在 TypeScript 中易于使用。 某些部分 仍在开发中。我们建议使用 sequelize-typescript 来弥合差距,直到我们的改进准备发布。

Sequelize 提供了自己的 TypeScript 定义。

请注意,仅支持 **TypeScript >= 4.1**。我们的 TypeScript 支持不遵循 SemVer。在至少一年内,我们将支持 TypeScript 版本,之后它们可能会在 SemVer 次要版本中被放弃。

由于 Sequelize 严重依赖运行时属性赋值,因此 TypeScript 在开箱即用时不会非常有用。需要大量手动类型声明才能使模型可行。

安装

为了避免与不同 Node 版本发生冲突,未包含 Node 的类型定义。您必须手动安装 @types/node

用法

**重要事项**:您必须在类属性类型定义中使用 declare 以确保 TypeScript 不发出这些类属性。请参阅 公共类字段的注意事项

Sequelize 模型接受两种泛型类型来定义模型的属性和创建属性。

import { Model, Optional } from 'sequelize';

// We don't recommend doing this. Read on for the new way of declaring Model typings.

type UserAttributes = {
id: number;
name: string;
// other attributes...
};

// we're telling the Model that 'id' is optional
// when creating an instance of the model (such as using Model.create()).
type UserCreationAttributes = Optional<UserAttributes, 'id'>;

class User extends Model<UserAttributes, UserCreationAttributes> {
declare id: number;
declare name: string;
// other attributes...
}

此解决方案冗长。Sequelize >=6.14.0 提供了新的实用程序类型,将大大减少必要的样板代码:InferAttributesInferCreationAttributes。它们将直接从模型中提取属性类型。

import { Model, InferAttributes, InferCreationAttributes, CreationOptional } from 'sequelize';

// order of InferAttributes & InferCreationAttributes is important.
class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
// 'CreationOptional' is a special type that marks the field as optional
// when creating an instance of the model (such as using Model.create()).
declare id: CreationOptional<number>;
declare name: string;
// other attributes...
}

关于 InferAttributesInferCreationAttributes 工作方式的重要事项:它们将选择类的所有声明属性,除了

  • 静态字段和方法。
  • 方法(任何类型为函数的内容)。
  • 那些类型使用品牌类型 NonAttribute 的属性。
  • 那些通过像这样使用 InferAttributes 排除的属性:InferAttributes<User, { omit: 'properties' | 'to' | 'omit' }>
  • 模型超类(但不是中间类!)声明的那些属性。如果您的某个属性与 Model 的某个属性同名,请更改其名称。执行此操作也可能导致问题。
  • Getter 和 Setter 不会自动排除。将其返回/参数类型设置为 NonAttribute,或将其添加到 omit 中以排除它们。

InferCreationAttributes 的工作方式与 InferAttributes 相同,但有一个例外:属性使用 CreationOptional 类型键入的属性将被标记为可选。请注意,接受 nullundefined 的属性不需要使用 CreationOptional

class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
declare firstName: string;

// there is no need to use CreationOptional on lastName because nullable attributes
// are always optional in User.create()
declare lastName: string | null;
}

// ...

await User.create({
firstName: 'Zoé',
// last name omitted, but this is still valid!
});

您只需要在类实例字段或 Getter 上使用 CreationOptionalNonAttribute

具有属性严格类型检查的最小 TypeScript 项目示例

/**
* Keep this file in sync with the code in the "Usage" section
* in /docs/manual/other-topics/typescript.md
*
* Don't include this comment in the md file.
*/
import {
Association, DataTypes, HasManyAddAssociationMixin, HasManyCountAssociationsMixin,
HasManyCreateAssociationMixin, HasManyGetAssociationsMixin, HasManyHasAssociationMixin,
HasManySetAssociationsMixin, HasManyAddAssociationsMixin, HasManyHasAssociationsMixin,
HasManyRemoveAssociationMixin, HasManyRemoveAssociationsMixin, Model, ModelDefined, Optional,
Sequelize, InferAttributes, InferCreationAttributes, CreationOptional, NonAttribute, ForeignKey,
} from 'sequelize';

const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');

// 'projects' is excluded as it's not an attribute, it's an association.
class User extends Model<InferAttributes<User, { omit: 'projects' }>, InferCreationAttributes<User, { omit: 'projects' }>> {
// id can be undefined during creation when using `autoIncrement`
declare id: CreationOptional<number>;
declare name: string;
declare preferredName: string | null; // for nullable fields

// timestamps!
// createdAt can be undefined during creation
declare createdAt: CreationOptional<Date>;
// updatedAt can be undefined during creation
declare updatedAt: CreationOptional<Date>;

// Since TS cannot determine model association at compile time
// we have to declare them here purely virtually
// these will not exist until `Model.init` was called.
declare getProjects: HasManyGetAssociationsMixin<Project>; // Note the null assertions!
declare addProject: HasManyAddAssociationMixin<Project, number>;
declare addProjects: HasManyAddAssociationsMixin<Project, number>;
declare setProjects: HasManySetAssociationsMixin<Project, number>;
declare removeProject: HasManyRemoveAssociationMixin<Project, number>;
declare removeProjects: HasManyRemoveAssociationsMixin<Project, number>;
declare hasProject: HasManyHasAssociationMixin<Project, number>;
declare hasProjects: HasManyHasAssociationsMixin<Project, number>;
declare countProjects: HasManyCountAssociationsMixin;
declare createProject: HasManyCreateAssociationMixin<Project, 'ownerId'>;

// You can also pre-declare possible inclusions, these will only be populated if you
// actively include a relation.
declare projects?: NonAttribute<Project[]>; // Note this is optional since it's only populated when explicitly requested in code

// getters that are not attributes should be tagged using NonAttribute
// to remove them from the model's Attribute Typings.
get fullName(): NonAttribute<string> {
return this.name;
}

declare static associations: {
projects: Association<User, Project>;
};
}

class Project extends Model<
InferAttributes<Project>,
InferCreationAttributes<Project>
> {
// id can be undefined during creation when using `autoIncrement`
declare id: CreationOptional<number>;

// foreign keys are automatically added by associations methods (like Project.belongsTo)
// by branding them using the `ForeignKey` type, `Project.init` will know it does not need to
// display an error if ownerId is missing.
declare ownerId: ForeignKey<User['id']>;
declare name: string;

// `owner` is an eagerly-loaded association.
// We tag it as `NonAttribute`
declare owner?: NonAttribute<User>;

// createdAt can be undefined during creation
declare createdAt: CreationOptional<Date>;
// updatedAt can be undefined during creation
declare updatedAt: CreationOptional<Date>;
}

class Address extends Model<
InferAttributes<Address>,
InferCreationAttributes<Address>
> {
declare userId: ForeignKey<User['id']>;
declare address: string;

// createdAt can be undefined during creation
declare createdAt: CreationOptional<Date>;
// updatedAt can be undefined during creation
declare updatedAt: CreationOptional<Date>;
}

Project.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: new DataTypes.STRING(128),
allowNull: false
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
},
{
sequelize,
tableName: 'projects'
}
);

User.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
name: {
type: new DataTypes.STRING(128),
allowNull: false
},
preferredName: {
type: new DataTypes.STRING(128),
allowNull: true
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
},
{
tableName: 'users',
sequelize // passing the `sequelize` instance is required
}
);

Address.init(
{
address: {
type: new DataTypes.STRING(128),
allowNull: false
},
createdAt: DataTypes.DATE,
updatedAt: DataTypes.DATE,
},
{
tableName: 'address',
sequelize // passing the `sequelize` instance is required
}
);

// You can also define modules in a functional way
interface NoteAttributes {
id: number;
title: string;
content: string;
}

// You can also set multiple attributes optional at once
type NoteCreationAttributes = Optional<NoteAttributes, 'id' | 'title'>;

// And with a functional approach defining a module looks like this
const Note: ModelDefined<
NoteAttributes,
NoteCreationAttributes
> = sequelize.define(
'Note',
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true
},
title: {
type: new DataTypes.STRING(64),
defaultValue: 'Unnamed Note'
},
content: {
type: new DataTypes.STRING(4096),
allowNull: false
}
},
{
tableName: 'notes'
}
);

// Here we associate which actually populates out pre-declared `association` static and other methods.
User.hasMany(Project, {
sourceKey: 'id',
foreignKey: 'ownerId',
as: 'projects' // this determines the name in `associations`!
});

Address.belongsTo(User, { targetKey: 'id' });
User.hasOne(Address, { sourceKey: 'id' });

async function doStuffWithUser() {
const newUser = await User.create({
name: 'Johnny',
preferredName: 'John',
});
console.log(newUser.id, newUser.name, newUser.preferredName);

const project = await newUser.createProject({
name: 'first!'
});

const ourUser = await User.findByPk(1, {
include: [User.associations.projects],
rejectOnEmpty: true // Specifying true here removes `null` from the return type!
});

// Note the `!` null assertion since TS can't know if we included
// the model or not
console.log(ourUser.projects![0].name);
}

(async () => {
await sequelize.sync();
await doStuffWithUser();
})();

Model.init 的情况

Model.init 要求为类型定义中声明的每个属性提供属性配置。

某些属性实际上不需要传递给 Model.init,以下是如何使此静态方法知道它们

  • 用于定义关联(Model.belongsToModel.hasMany 等)的方法已经处理了必要的外键属性的配置。无需使用 Model.init 配置这些外键。使用 ForeignKey<> 品牌类型使 Model.init 意识到无需配置外键。

    import {
    Model,
    InferAttributes,
    InferCreationAttributes,
    DataTypes,
    ForeignKey,
    } from 'sequelize';

    class Project extends Model<InferAttributes<Project>, InferCreationAttributes<Project>> {
    id: number;
    userId: ForeignKey<number>;
    }

    // this configures the `userId` attribute.
    Project.belongsTo(User);

    // therefore, `userId` doesn't need to be specified here.
    Project.init(
    {
    id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    },
    },
    { sequelize },
    );
  • Sequelize 管理的时间戳属性(默认情况下,createdAtupdatedAtdeletedAt)不需要使用 Model.init 进行配置,不幸的是 Model.init 无法知道这一点。我们建议您使用最少的必要配置来消除此错误。

    import { Model, InferAttributes, InferCreationAttributes, DataTypes } from 'sequelize';

    class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
    id: number;
    createdAt: Date;
    updatedAt: Date;
    }

    User.init(
    {
    id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    },
    // technically, `createdAt` & `updatedAt` are added by Sequelize and don't need to be configured in Model.init
    // but the typings of Model.init do not know this. Add the following to mute the typing error:
    createdAt: DataTypes.DATE,
    updatedAt: DataTypes.DATE,
    },
    { sequelize },
    );

在没有属性严格类型的情况下使用

Sequelize v5 的类型定义允许您定义模型而不为属性指定类型。这对于向后兼容以及您认为属性的严格类型不值得的情况仍然是可能的。

/**
* Keep this file in sync with the code in the "Usage without strict types for
* attributes" section in /docs/manual/other-topics/typescript.md
*
* Don't include this comment in the md file.
*/
import { Sequelize, Model, DataTypes } from 'sequelize';

const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');

class User extends Model {
declare id: number;
declare name: string;
declare preferredName: string | null;
}

User.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
name: {
type: new DataTypes.STRING(128),
allowNull: false,
},
preferredName: {
type: new DataTypes.STRING(128),
allowNull: true,
},
},
{
tableName: 'users',
sequelize, // passing the `sequelize` instance is required
},
);

async function doStuffWithUserModel() {
const newUser = await User.create({
name: 'Johnny',
preferredName: 'John',
});
console.log(newUser.id, newUser.name, newUser.preferredName);

const foundUser = await User.findOne({ where: { name: 'Johnny' } });
if (foundUser === null) return;
console.log(foundUser.name);
}

Sequelize#define 的用法

在 v5 之前的 Sequelize 版本中,定义模型的默认方法涉及使用 Sequelize#define。仍然可以使用它来定义模型,并且您还可以使用接口为这些模型添加类型定义。

/**
* Keep this file in sync with the code in the "Usage of `sequelize.define`"
* section in /docs/manual/other-topics/typescript.md
*
* Don't include this comment in the md file.
*/
import { Sequelize, Model, DataTypes, CreationOptional, InferAttributes, InferCreationAttributes } from 'sequelize';

const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');

// We recommend you declare an interface for the attributes, for stricter typechecking

interface UserModel extends Model<InferAttributes<UserModel>, InferCreationAttributes<UserModel>> {
// Some fields are optional when calling UserModel.create() or UserModel.build()
id: CreationOptional<number>;
name: string;
}

const UserModel = sequelize.define<UserModel>('User', {
id: {
primaryKey: true,
type: DataTypes.INTEGER.UNSIGNED,
},
name: {
type: DataTypes.STRING,
},
});

async function doStuff() {
const instance = await UserModel.findByPk(1, {
rejectOnEmpty: true,
});

console.log(instance.id);
}

实用程序类型

请求模型类

ModelStatic 旨在用于为模型 *类* 键入。

以下是一个请求模型类并返回该类中定义的主键列表的实用程序方法示例。

import {
ModelStatic,
ModelAttributeColumnOptions,
Model,
InferAttributes,
InferCreationAttributes,
CreationOptional,
} from 'sequelize';

/**
* Returns the list of attributes that are part of the model's primary key.
*/
export function getPrimaryKeyAttributes(model: ModelStatic<any>): ModelAttributeColumnOptions[] {
const attributes: ModelAttributeColumnOptions[] = [];

for (const attribute of Object.values(model.rawAttributes)) {
if (attribute.primaryKey) {
attributes.push(attribute);
}
}

return attributes;
}

class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
id: CreationOptional<number>;
}

User.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
},
{ sequelize },
);

const primaryAttributes = getPrimaryKeyAttributes(User);

获取模型的属性

如果需要访问给定模型的属性列表,则需要使用 Attributes<Model>CreationAttributes<Model>

它们将返回作为参数传递的模型的属性(和创建属性)。

不要将它们与 InferAttributesInferCreationAttributes 混淆。这两个实用程序类型仅应在模型定义中使用,以根据模型的公共类字段自动创建属性列表。它们仅适用于基于类的模型定义(使用 Model.init 时)。

Attributes<Model>CreationAttributes<Model> 将返回任何模型的属性列表,无论它们是如何创建的(无论是 Model.init 还是 Sequelize#define)。

以下是一个请求模型类和属性名称并返回相应的属性元数据的实用程序函数示例。

import {
ModelStatic,
ModelAttributeColumnOptions,
Model,
InferAttributes,
InferCreationAttributes,
CreationOptional,
Attributes,
} from 'sequelize';

export function getAttributeMetadata<M extends Model>(
model: ModelStatic<M>,
attributeName: keyof Attributes<M>,
): ModelAttributeColumnOptions {
const attribute = model.rawAttributes[attributeName];
if (attribute == null) {
throw new Error(`Attribute ${attributeName} does not exist on model ${model.name}`);
}

return attribute;
}

class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
id: CreationOptional<number>;
}

User.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
autoIncrement: true,
primaryKey: true,
},
},
{ sequelize },
);

const idAttributeMeta = getAttributeMetadata(User, 'id'); // works!

// @ts-expect-error
const nameAttributeMeta = getAttributeMetadata(User, 'name'); // fails because 'name' is not an attribute of User