| 48 | // Using `this` typing in class methods |
| 49 | |
| 50 | function thisParameterPattern() { |
| 51 | interface MySchema { |
| 52 | property1: string; |
| 53 | } |
| 54 | |
| 55 | class MyClass { |
| 56 | // Instance method typed with correct `this` type |
| 57 | myMethod(this: MyCombinedDocument) { |
| 58 | return this.property1; |
| 59 | } |
| 60 | |
| 61 | // Static method typed with correct `this` type |
| 62 | static myStatic(this: MyCombinedModel) { |
| 63 | return 42; |
| 64 | } |
| 65 | |
| 66 | |
| 67 | // TypeScript does NOT allow `this` parameters in getters/setters. |
| 68 | // So we show an example error here. |
| 69 | get myVirtual() { |
| 70 | // @ts-expect-error Property 'property1' does not exist on type 'MyClass'. |
| 71 | return this.property1; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | const schema = new Schema<MySchema>({ property1: String }); |
| 76 | schema.loadClass(MyClass); |
| 77 | |
| 78 | type MyCombined = MySchema & MyClass; |
| 79 | type MyCombinedModel = Model<MyCombined> & typeof MyClass; |
| 80 | type MyCombinedDocument = Document & MyCombined; |
| 81 | |
| 82 | const MyModel = model<MyCombinedDocument, MyCombinedModel>('MyClass2', schema as any); |
| 83 | |
| 84 | // Test static |
| 85 | expect(MyModel.myStatic()).type.toBe<number>(); |
| 86 | |
| 87 | const doc = new MyModel({ property1: 'test' }); |
| 88 | |
| 89 | // Instance method returns string |
| 90 | expect(doc.myMethod()).type.toBe<string>(); |
| 91 | |
| 92 | // Schema field is typed correctly |
| 93 | expect(doc.property1).type.toBe<string>(); |
| 94 | |
| 95 | |
| 96 | // Getter works at runtime, but TypeScript can't type `this` in getters. |
| 97 | // So we accept `any`. |
| 98 | const virtual = doc.myVirtual; |
| 99 | expect(virtual).type.toBe<any>(); |
| 100 | } |
| 101 | |
| 102 | |
| 103 | // ---------------------------------------------------------- |