【问题标题】:typescript generic method type annotation打字稿泛型方法类型注释
【发布时间】:2021-10-27 13:39:01
【问题描述】:

在以下方法中,我遇到的问题是找不到更改参数的类型而不会出错。这是一个普通的 nestjs 服务,它是通用的,应该涵盖标准的 crud 功能。但在更新功能中,我没有找到用于更改的通用类型。

如果我可以使用 Model T 类型对我来说是合乎逻辑的,不幸的是猫鼬不允许。

欢迎提出想法,在此先感谢您。

  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();
    }
  }

这里是完整的 CRUD 服务类

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();
    }
  }
}

【问题讨论】:

    标签: node.js typescript mongodb mongoose nestjs


    【解决方案1】:

    这是猫鼬的updateOne typedef:

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

    它们引用了一个类型UpdateQuery&lt;T&gt;。这就是你要找的东西吗?

    【讨论】:

    • perfekt that works :) 在创建方法上,我使用引用类型(字符串 | 记录)但它不起作用。 ```` async createG( object: string | Record, ): Promise { try { return await this.model.create(object); } catch (err) { throw new InternalServerErrorException(); } } ````
    • 如果它有效,那么您可以将我的答案标记为已接受
    猜你喜欢
    • 1970-01-01
    • 2021-11-26
    • 2021-06-09
    • 2021-08-13
    • 1970-01-01
    • 2017-03-03
    • 2020-05-26
    • 1970-01-01
    • 2020-06-29
    相关资源
    最近更新 更多