首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型“Document<any>”不能赋值给类型“Pick<Pick<_LeanDocument<TicketDoc>”

类型“Document<any>”不能赋值给类型“Pick<Pick<_LeanDocument<TicketDoc>”
EN

Stack Overflow用户
提问于 2021-02-24 03:40:15
回答 1查看 1.1K关注 0票数 1

我有一个错误,在我的终端上就像泥巴一样清晰:

TSError:⨯无法编译TypeScript:

订单-depl-9fbcb84ff-ngt2z订单

src/models/ticket.ts(47,5):错误TS2322:类型'Document‘不可分配给类型'Pick,“

_

id“|”

_

_

v“| "id”|“标题”|“价格”>| QuerySelector<...> |未定义‘。

订单-depl-9fbcb84ff-ngt2z订单

类型'Document‘缺少'Pick’类型的以下属性,“

_

id“|”

_

_

v“| "id”| " title“| " price ">':标题,价格

它引用了这个模型文件:

代码语言:javascript
复制
import mongoose from 'mongoose';
import { Order, OrderStatus } from './order';

interface TicketAttrs {
  title: string;
  price: number;
}

export interface TicketDoc extends mongoose.Document {
  title: string;
  price: number;
  isReserved(): Promise;
}

interface TicketModel extends mongoose.Model {
  build(attrs: TicketAttrs): TicketDoc;
}

const ticketSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true,
    min: 0
  }
}, {
  toJSON: {
    transform(doc, ret) {
      ret.id = ret._id;
      delete ret._id;
    }
  }
});

ticketSchema.statics.build = (attrs: TicketAttrs) => {
  return new Ticket(attrs);
};
// Run query to look at all orders. Find an order where the 
// ticket is the ticket just found *and* the order status is *not* cancelled.
// If we find an order from that means the ticket *is* reserved
ticketSchema.methods.isReserved = async function () {
  // this === the ticket document that I just called 'isReserved' on
  const existingOrder = await Order.findOne({
    ticket: this,
    status: {
      $in: [
        OrderStatus.Created,
        OrderStatus.AwaitingPayment,
        OrderStatus.Complete
      ]
    }
  });

  return !!existingOrder;
};

const Ticket = mongoose.model('Ticket', ticketSchema);

export { Ticket };

我不知道我在哪里犯了语法错误,我也不知道这种类型的

就是。看起来问题是

不是

但应等于

,除了它不是。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-24 04:03:15

哇,这是TypeScript中的一个陷阱,你必须有深刻的知识才能弄清楚。下面是如何消除错误的方法:

代码语言:javascript
复制
// Run query to look at all orders. Find an order where the 
// ticket is the ticket just found *and* the order status is *not* cancelled.
// If we find an order from that means the ticket *is* reserved
ticketSchema.methods.isReserved = async function () {
  // this === the ticket document that I just called 'isReserved' on
  const existingOrder = await Order.findOne({
    //@ts-ignore
    ticket: this,
    status: {
      $in: [
        OrderStatus.Created,
        OrderStatus.AwaitingPayment,
        OrderStatus.Complete
      ]
    }
  });

  return !!existingOrder;
};

我通常不会这样做,因为它绕过了我们所依赖的TS检查,以确保一切都是类型安全的。不过现在,它起作用了,因为这个错误很奇怪,因为从技术上讲,这不是我在开发代码时做错了什么,我猜只是TypeScript的怪癖。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66339949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档