| 3 | |
| 4 | // Basic usage of `loadClass` with TypeScript |
| 5 | function basicLoadClassPattern() { |
| 6 | class MyClass { |
| 7 | myMethod() { return 42; } |
| 8 | static myStatic() { return 42; } |
| 9 | get myVirtual() { return 42; } |
| 10 | } |
| 11 | |
| 12 | const schema = new Schema({ property1: String }); |
| 13 | schema.loadClass(MyClass); |
| 14 | |
| 15 | interface MySchema { |
| 16 | property1: string; |
| 17 | } |
| 18 | |
| 19 | |
| 20 | // `loadClass()` does NOT update TS types automatically. |
| 21 | // So we must manually combine schema fields + class members. |
| 22 | type MyCombined = MySchema & MyClass; |
| 23 | |
| 24 | // The model type must include statics from the class |
| 25 | type MyCombinedModel = Model<MyCombined> & typeof MyClass; |
| 26 | |
| 27 | // A document must combine Mongoose Document + class + schema |
| 28 | type MyCombinedDocument = Document & MyCombined; |
| 29 | |
| 30 | // Cast schema to satisfy TypeScript |
| 31 | const MyModel = model<MyCombinedDocument, MyCombinedModel>('MyClass', schema as any); |
| 32 | |
| 33 | // Static function should work |
| 34 | expect(MyModel.myStatic()).type.toBe<number>(); |
| 35 | |
| 36 | // Instance method should work |
| 37 | const doc = new MyModel(); |
| 38 | expect(doc.myMethod()).type.toBe<number>(); |
| 39 | |
| 40 | // Getter should work |
| 41 | expect(doc.myVirtual).type.toBe<number>(); |
| 42 | |
| 43 | // Schema property should be typed |
| 44 | expect(doc.property1).type.toBe<string>(); |
| 45 | } |
| 46 | |
| 47 | |
| 48 | // Using `this` typing in class methods |