【问题标题】:Type 'Document<any, any, any>' is missing the following properties from type 'IAccount': _type, pai类型“文档<any、any、any>”缺少类型“IAccount”的以下属性:_type、pai
【发布时间】:2021-09-24 06:13:35
【问题描述】:

我不清楚这个错误在说什么:

Type 'Document' 缺少以下属性 来自“IAAccount”类型:_type,pai

47 返回新帐户;

错误与此方法有关:

async createAccount(
    dbSession: ClientSession,
    pai: string
  ): Promise<IAccount> {
    const newAccount = new this.Model(
      new (class implements IAccount {
        _id = mongoose.Types.ObjectId();
        _type: "Account" = "Account";
        pai = pai;
      })()
    );
    await newAccount.save(dbSession);
    return newAccount;
  }

我也收到一个相关的错误提示:

重载 1 of 3, '(options?: SaveOptions | undefined): Promise>',给出了以下错误。 “ClientSession”类型与“SaveOptions”类型没有共同的属性。重载 2 of 3, '(options?: SaveOptions | undefined, fn?: 回调> | undefined): void',给出了 以下错误。 “ClientSession”类型与“SaveOptions”类型没有共同的属性。重载 3 of 3, '(fn?: Callback> | undefined): void',给出以下错误。 “ClientSession”类型的参数不可分配给“Callback>”类型的参数。

46 等待 newAccount.save(dbSession);

但它似乎与AccountSchema 模型有关,它的尖括号中有一个any

interface IAccount {
  _id: ID;
  _type: "Account";

  pai: string;
  disabledOn?: Date;
  tags?: ITag[];

  schemaVersion?: number;
  createdOn?: Date;
  updatedOn?: Date;
}

const AccountSchemaFields: Record<keyof IAccount, any> = {
  _id: Types.ObjectId,
  _type: { type: String, default: "Account" },

  pai: String,
  disabledOn: { type: Date, required: false },
  tags: { type: [TagSchema], required: false },

  schemaVersion: { type: Number, default: 1 },
  createdOn: Date,
  updatedOn: Date,
};

我觉得保留any 的类型从来都不是一个好规则,但不确定用什么替换它,如果这确实是问题。

或者这个错误是说我缺少 Mongoose IAccount 文档?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您实际上没有正确使用类型,对于ClientSession 问题,这是因为您没有将dbSession 作为{session: dbSession} 传递

    所以解决方案是

     await newAccount.save({ session: dbSession});
    

    而第二个,错误很简单,newAccount 不完全满足IAccount

    但您可以通过以下方式规避这一点

    async function createAccount(
        dbSession: ClientSession,
        pai: string
      ): Promise<Pick<IAccount, '_id'>> {
        const newAccount = new Model(
          new (class implements IAccount {
            _id = Types.ObjectId();
            _type: "Account" = "Account";
            pai = pai;
          })()
        );
        await newAccount.save({session: dbSession});
        return newAccount
      }
    

    【讨论】:

    • 当我实施您的第二个解决方案时,我在许多其他包含account.pai 的文件上得到Property 'pai' does not exist on type 'Pick&lt;IAccount, "_id"&gt;'. 257 account.pai,
    • @Daniel,我会建议你将createAccount 的所有调用点声明到这个`(结果为IAccount).pai`。 let result = await createAccount() as IAccount
    猜你喜欢
    • 2021-10-02
    • 2019-12-24
    • 1970-01-01
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多