tsc不识别mongoose方案上的虚拟

bxgwgixi  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(124)

我喜欢虚拟 Mongoose ,但我不能让它在打字稿工作。
我使用mongoose的InferSchemaType来创建接口,如mongoose documentation中的“另一种方法:“中所述
TSC不会将它们识别为接口中的字段。
我尝试了两种建议的方式(见下面的代码)。

import {connect, InferSchemaType, Schema, model} from 'mongoose';

const url = 'mongodb://admin:admin@0.0.0.0:27017/';

export const DBS_Actor = new Schema(
  {
    firstName: String,
    lastName: String,
  },
  {
    virtuals: {
      fullName: {
        get() {
          return this.firstName + ' ' + this.lastName;
        },
      },
    },
  }
);

DBS_Actor.virtual('tagname').get(function () {
  return 'Secrete Agent 007';
});

export type IActor = InferSchemaType<typeof DBS_Actor>;
export const Actor = model<IActor>('User', DBS_Actor);

run().catch(err => console.log(err));
async function run() {
  await connect(url);

  const actor = new Actor({
    firstName: 'jojo',
    lastName: 'kiki',
  });
  await actor.save();
  console.log(actor.toJSON()); // {firstName: 'jojo', lastName: 'kiki', _id: new ObjectId("62e52b18d41b2bd4d2bd08d8"),  __v: 0  }
  console.log(actor.firstName); // jojo
  //  console.log(actor.fullname); //TSC error TS2339: Property 'fullname' does not exist on typ
  //  console.log(actor.tagname); //TSC error TS2339: Property 'tagname' does not exist on type...
}
huwehgph

huwehgph1#

如果要在类型上使用其他字段,可以扩展类型:

export type IActor = InferSchemaType<typeof DBS_Actor> & {
firstName: String
};

相关问题