Alessandro Rhomberg
Alessandro Rhomberg

Reputation: 155

typescript generic method type annotation

In the following method I have the problem that I can't find a type for the changes parameter without getting an error. This is a normal nestjs service that is generic and should cover the standard crud functions. But in the update function i dont find a generic type for the changes.

It would be logical for me if I can use the type Model T, unfortunately the mongoose does not allow.

Open to ideas, thank you in advance.

  async updateOne(
    conditions: Partial<Record<keyof T, unknown>>,
    changes: any, // type for cahnges
    // projection: string | Record<string, unknown> = {},
    // options: Record<string, unknown> = {},
  ): Promise<T> {
    try {
      return await this.model.findOneAndUpdate(
        conditions as FilterQuery<T>,
        changes,
      );
    } catch (err) {
      console.log('generic service error:  ' + err);
      throw new InternalServerErrorException();
    }
  }

Here the complete CRUD Service class

import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { Document, FilterQuery, Model } from 'mongoose';

@Injectable()
export abstract class GenericCrudService<T extends Document> {
  constructor(private readonly model: Model<T>) {}

  async findAll(
    conditions: Partial<Record<keyof T, unknown>>,
    projection: string | Record<string, unknown> = {},
    options: Record<string, unknown> = {},
  ): Promise<T[]> {
    try {
      return await this.model.find(
        conditions as FilterQuery<T>,
        projection,
        options,
      );
    } catch (err) {
      console.log('generic error:  ' + err);
      throw new InternalServerErrorException();
    }
  }

  async updateOne(
    conditions: Partial<Record<keyof T, unknown>>,
    changes: any,
    // projection: string | Record<string, unknown> = {},
    // options: Record<string, unknown> = {},
  ): Promise<T> {
    try {
      return await this.model.findOneAndUpdate(
        conditions as FilterQuery<T>,
        changes,
      );
    } catch (err) {
      console.log('generic service error:  ' + err);
      throw new InternalServerErrorException();
    }
  }
}

Upvotes: 0

Views: 443

Answers (1)

HKG
HKG

Reputation: 328

This is mongoose's updateOne typedef:

 updateOne(update?: UpdateQuery<this> | UpdateWithAggregationPipeline, options?: QueryOptions | null, callback?: Callback): Query<any, this>;

They reference a type UpdateQuery<T>. Is that what are you're looking for?

Upvotes: 1

Related Questions