1

I try to add a static method to my Model, but if I do it, I got this Error: An interface may only extend a class or another interface.

This is my code:

import * as mongoose from 'mongoose';
import {IPermission} from './IPermission';

export interface IRoleDocument extends mongoose.Document {
    name: string,
    inherit_from: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Role'
    },
    permissions: Array<IPermission>
};

export interface IRole extends mongoose.Model<IRoleDocument> {

};

Error comes from export interface IRole extends mongoose.Model<IRoleDocument>

Greetz

R3Tech
  • 743
  • 2
  • 9
  • 22

1 Answers1

1

As far I I know it is impossible to inherit from intersection/union types in typescript. And in case of mongoose type definitions mongoose.Model<T> is declared as intersection type:

type ModelConstructor<T> = IModelConstructor<T> & events.EventEmitter;

For examples of how to use mongoose in typescript you can check this topic on SA

But you still can use intersection instead of inheritance to get your required interface, like this:

interface IRoleDefinition
{
    myExtraProperty: string;
}

type IRole = mongoose.Model<IRoleDocument> & IRoleDefinition; 

More info about intersection types vs inheritance: github

Community
  • 1
  • 1
Amid
  • 21,508
  • 5
  • 57
  • 54
  • I read the thread of SA. But there is no declaration for static methods. If I did it on your example the IRoleDefinition defines are found but not static. And the member in IRoleDocument doesn't exists for TypeScript. – R3Tech Aug 21 '16 at 09:09
  • I am not an expert in mongoose. To help you I would like to clarify the following points: 1) Interface cannot have both static and instance methods declared at the same time - two separate interfaces are usually used 2) it is impossible to extend mongoose.Model as it is intersection type. – Amid Aug 21 '16 at 10:14
  • I googled how to create static methods that typescript find and the way I write was the answer... maybe a depracted way. I know that Interfaces only can have one of the method types but how to tell typescript which I mean? To the second point, im not clearly sure... – R3Tech Aug 21 '16 at 12:21