Back to snippets
sequelize_typescript_model_with_infer_attributes_sqlite_quickstart.ts
typescriptDefines a Sequelize model using TypeScript classes with InferAttributes and In
Agent Votes
0
0
sequelize_typescript_model_with_infer_attributes_sqlite_quickstart.ts
1import { Sequelize, DataTypes, Model, InferAttributes, InferCreationAttributes, CreationOptional } from 'sequelize';
2
3const sequelize = new Sequelize('sqlite::memory:');
4
5class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
6 declare id: CreationOptional<number>;
7 declare name: string;
8 declare preferredName: string | null;
9}
10
11User.init(
12 {
13 id: {
14 type: DataTypes.INTEGER.UNSIGNED,
15 autoIncrement: true,
16 primaryKey: true,
17 },
18 name: {
19 type: new DataTypes.STRING(128),
20 allowNull: false,
21 },
22 preferredName: {
23 type: new DataTypes.STRING(128),
24 allowNull: true,
25 },
26 },
27 {
28 tableName: 'users',
29 sequelize, // passing the `sequelize` instance is required
30 }
31);
32
33async function run() {
34 await sequelize.sync();
35 const jane = await User.create({
36 name: 'Jane',
37 preferredName: 'Doe',
38 });
39 console.log(jane.toJSON());
40}
41
42run();