types/sequelize

Canonical examples of instance methods?

Closed this issue · 3 comments

Not sure whether I'm missing something really obvious here, but my models don't type check if I refer to the model classes within their methods.

import { Model, DataTypes } from "sequelize";
import sequelize from "./lib/sequelize";

class Message extends Model {
  id: number;
  text: string;
  
  createFromEvent(event: string) {
    return Message.create({ text: event });
  }
}

Message.init({ text: DataTypes.STRING }, { sequelize });

The call to Message.create fails with the following error.

The 'this' context of type 'typeof Message' is not assignable to method's 'this' of type '(new () => Message) & typeof Model'

I'm suffering from the fact that I'm not well versed in TypeScript and this error message is not transparent to me.

  • (new () => Message) seems to be the type signature that would describe a constructor/class that returns Message type objects. In which case, that should be satisfied by the fact that this is the Message class.
  • typeof Model which would presumably be equivalent to (new () => Model). I would have imagined that this was also satisfied because the Message class inherits from the model class.

I'm in the process of converting existing Sequelize code to TypeScript and so I expect that one of the abstractions already in place is tripping me up. Either way, it would be great to have a reference example of a typed model definition that includes these kind of methods.

What TS version?

  • Was initially using TS 2.4.1, but then saw the peer-dependency warning and switched to 2.4.0.
  • Using Sequelize 4.2.0
  • Using 2d9120f of @types/sequelize

@felixfbecker Hope that helps.

There are bugs in 2.4.0. I corrected the peerDependency range.
See microsoft/TypeScript#16790