sequelize.jsflowtypeflow-typed

How can I properly annotate a Sequelize model with flow-typed?


I'm using flow-typed with sequelize^4.44.3. It's complaining because the Model has no parameters. But that seems to be the standard way to create models with Sequelize, so what am I doing wrong?

enter image description here


Solution

  • Let's take a look at the libdef.

    As you can see, the Model class is defined as:

    class Model<TAttributes, TInitAttributes = TAttributes, TPlainAttributes = TAttributes>
    

    There are three type parameters here, the second two of which are optional because the default to the first. So let's break them down one-by-one:

    TAttributes

    This is an object type that represents the attributes of your model class. I can see in your screenshot that you have a string field called name. Let's assume for the sake of example that you also have a count of participants in your Conversation. So your TAttributes for a model with just those two fields might look like this:

    type ConversationAttributes = {
      name: string,
      participants: number,
    };
    

    Now we can take this type which defines our attributes and pass it into the Model class as a type parameter to define our model:

    class Conversation extends Model<ConversationAttributes> {
      // ...
    

    This should work fine, but we have some other options as well:

    TInitAttributes

    This defaults to TAttributes, so in our example it will be ConversationAttributes, so we don't need to specify it in this case.

    TInitAttributes is the type used for construction of a new record. If this type is different from TAttributes for some reason, you can specify it here (probably in the case of some computed property that would exist on TAttributes but would make no sense on TInitAttributes.

    TPlainAttributes

    This defaults to TAttributes, so in our example it will be ConversationAttributes, so we don't need to specify it in this case.

    TPlainAttributes is the return type of the toJSON method and it's also the return type of the get method when passing {plain: true} as the options. If the "plain" serialization of our attributes differs from TAttributes in some way, we could specify the type of the "plain" version here.