Reputation: 31
I have this problem with typescript and can not understand what is wrong:
type Dogs = {bark: true};
type Cats = {meow: true};
........
.then((data: [Dogs, Cats][]) => {
const [dogs, cats] = data;
display(dogs, cats));
})
........
const display = (dogs: any, cats: any) => {
return ....
}
For now, everything is ok. When display function is written like this (dogs: any, cats: any) everything is fine, but if I change display function to:
const display = (dogs: Dogs, cats: Cats) => {
return ....
}
I receive an error in destructuring line (const [dogs, cats] = data;) that "dogs doesn't have meow key and cats doesn't have bark key"???
What I'm doing wrong?
Upvotes: 2
Views: 6938
Reputation: 3526
data
is an array of [Dog, Cat]
, so destructuring const [dogs, cats] = data;
would lead to assign the first element of data
to dogs
and second element to cats
. ie, extracted value dogs
is of type [Dog, Cat]
. And extracted cats
is of type [Dog, Cat]
.
const [dog, cat] = data[0];
would correctly destructure to give correct dog and cat value. If you are tying to get the collection of dogs and cats into separate arrays, you can use reduce
.
type Dogs = {bark: true};
type Cats = {meow: true};
const data: [Dogs, Cats][] = [[{bark: true}, {meow: true}]]
const display = (dogs: Dogs, cats: Cats) => {
return 'dummy'
}
let result: {dogs: Dogs[], cats: Cats[]} = {dogs: [], cats: []};
data.reduce((acc, curr) => {
const [dog, cat] = curr;
acc.dogs.push(dog);
acc.cats.push(cat);
return acc
}, result);
Upvotes: 2
Reputation: 14007
Your data
parameter of then
is an array of a tuple [Dogs, Cats]
. If this is intended, you need to pick an item before deconstruction:
const [dogs, cats] = data[0];
If this is not intended, just annotate the type as a tuple:
.then((data: [Dogs, Cats])
Upvotes: 1