Reputation: 424
I have a POST
road that received an array
of Queue
. I want to filter them before to create them inside my data source.
I tried to do it like this:
async createarraywithcheck(
@requestBody(/*...*/)
queues: [Omit<Queue, 'id'>],
): Promise<Queue[]> {
queues = queues.filter(queue => queue.title.length < 10); //error here
return this.queueRepository.createAll(queues);
}
But I get this error:
Type 'Pick<Queue, "getId" | "getIdObject" | "toJSON" | "toObject" | "title">[]'
is not assignable to type
'[Pick<Queue, "getId" | "getIdObject" | "toJSON" | "toObject" |"title">]'.
Target requires 1 element(s) but source may have fewer.ts(2322)
I do not understand the difference, to me they are both array of Pick<Queue, ....>
.
How can I fix that?
Upvotes: 0
Views: 145
Reputation: 2344
As discussed, problem comes from the type of your queues
argument.
You set the type as [Omit<Queue, 'id'>]
, which is a tuple. Not any tuple, but a tuple with exactly one argument.
In javascript, a tuple is basically an array. If you filter this array, what happens if none of the items pass the condition? well, you return an empty array.
Since you are re-assigning to queues
, you may be doing the following:
queues = [] // here you have the error
Solution is one of the below:
const filteredQueues: Omit<Queue, 'id'>[] = queues.filter(queue => queue.title.length < 10)
queues: Omit<Queue, 'id'>[]
Upvotes: 1