2

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?

5
  • 3
    .then((data: [Dogs, Cats]) => { you miswrote your type Commented Sep 1, 2020 at 6:46
  • data: [Dogs, Cats][] is an array of tuples, each tuple is [Dogs, Cats]. If you destructure as const [dogs, cats] = data; then dogs will hold the first tuple and cats will hold the second tuple. I'm not sure what you need but it's likely not an array of tuples. Either a plain tuple or an array. Commented Sep 1, 2020 at 6:47
  • Inside your then you are trying to deconstruct array of arrays into two variables. Each variable interpreted like array. So you should try just data: [Dogs, Cats]. Commented Sep 1, 2020 at 6:47
  • No, it is typed correctly. Commented Sep 1, 2020 at 6:49
  • data: [Dogs, Cats] does not work. Commented Sep 1, 2020 at 6:51

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.