LoginSignup
2
2

More than 3 years have passed since last update.

[sequelize-cli] typescriptで使いたい!

Posted at

sequelizeを使う時はcliでマイグレーションすることが多いと思いますが、出力されるファイルはjsです。イケてないですね(諸説)

sequelize-cli-typescript という素晴らしいモジュールもありますが、最終更新が2年前なので惜しいです。

とりあえず model を作成する

npx sequelize-cli init


こうなる
 |- models
 |- migrations
 |- seeders
 |- config
npx sequelize-cli model:generate --name member --attributes name:string --underscored

id, name を持つ member モデルが作成されます。ついでにindex.jsも。

'use strict';
module.exports = (sequelize, DataTypes) => {
  const member = sequelize.define('member', {
    name: DataTypes.STRING
  }, {
    underscored: true,
  });
  member.associate = function(models) {
    // associations can be defined here
  };
  return member;
};

オプション
- underscored: 自動生成の created_atupdated_at がスネークケースになります。

型定義をつける

公式documentの typescript を読むと、

  • class
  • .define

のどちらかを使う必要がありそうです。生成されたものが define なので、それに合わせた型定義ファイルを作成します。

階層

models
 |- index.js
 |- member.js
 |- index.d.ts <-作成
import { Model, BuildOptions } from 'sequelize';

/* モデルの数作成する */
interface MemberModel extends Model {
    readonly id: number;
    name: string;
    readonly created_at: date;
    readonly updated_at: date;
}

type MemberModelStatic = typeof Model & {
    new (values?: object, options?: BuildOptions): MemberModel;
}
/* --------------- */

interface DBModel {
    member: MemberModelStatic;
}

declare const db: DBModel;
export = db;

こうすることで、index.js で module.exports されている db に型定義がつきます。

DBModel のキーはモデル名と同一にする必要があります。

使う

findcreate などの補完が出てくれます。

スクリーンショット 2020-06-04 11.40.20.png

ただし、find 系の返り値が any になります。(死)

嫌な人は class の書き方か、typeorm を使おう。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2