Tengo un error que es claro como el barro en mi terminal:
TSError: ⨯ No se puede compilar TypeScript: [orders-depl-9fbcb84ff-ngt2z orders] src/models/ticket.ts(47,5): error TS2322: el tipo 'Documento' no se puede asignar al tipo 'Pick<Pick<_LeanDocument, "_id" | "__v" | "identificación" | "título" | "precio" | "estáReservado">, "_id" | "__v" | "identificación" | "título" | "precio"> | Selector de consultas<...> | indefinido'. [orders-depl-9fbcb84ff-ngt2z orders] Al tipo 'Documento' le faltan las siguientes propiedades del tipo 'Pick<Pick<_LeanDocument, "_id" | "__v" | "identificación" | "título" | "precio" | "estáReservado">, "_id" | "__v" | "identificación" | "título" | "precio">': título, precio
Hace referencia a este archivo de modelo:
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<boolean>; } interface TicketModel extends mongoose.Model<TicketDoc> { 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<TicketDoc, TicketModel>('Ticket', ticketSchema); export { Ticket }; No veo dónde he cometido un error de sintaxis en ninguna parte y no tengo idea de qué es este tipo de Pick . Parece que el problema es que el ticket no es un ticket , pero debería ser igual a this , excepto que no lo es.
Wow, esta fue una de esas trampas en TypeScript donde tienes que tener un conocimiento profundo para averiguarlo. Así que así es como haces que el error desaparezca:
// 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; };Normalmente no haría esto, ya que omite las comprobaciones de TS en las que confiamos para asegurarnos de que todo sea seguro. Sin embargo, por ahora funciona, ya que el error fue simplemente extraño, ya que técnicamente no fue nada que haya hecho mal al desarrollar el código, solo una peculiaridad de TypeScript, supongo.
Sé que ha pasado mucho tiempo. Pero vi esta respuesta en las preguntas y respuestas de Udemy del usuario Jonathan y creo que es mejor que deshabilitar la verificación de TS:
No soy un gran fanático de ts-ignore por las razones expuestas anteriormente por Korey.
Sospecho que la causa del problema es el método adicional isReserved() agregado a un documento de Ticket.
Por lo tanto, en lugar de buscar por el documento del boleto (este), busqué a través de la identificación del documento del boleto (este.id). Esto debería funcionar bien.
ticketSchema.methods.isReserved = async function() { const existingOrder = await Order.findOne({ ticket: this.id, // Ticket id status: { $in: [ OrderStatus.Created, OrderStatus.AwaitingPayment, OrderStatus.Complete ] } }) return !!existingOrder }