Skip to content

Canonical examples of instance methods? #112

Closed

Description

@danprince

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.

Activity

  1. felixfbecker commented on Jul 8, 2017

    @felixfbecker
    Collaborator

    What TS version?

  2. danprince commented on Jul 8, 2017

    @danprince
    Author
    • 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.

  3. felixfbecker commented on Jul 8, 2017

    @felixfbecker
    Collaborator

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions