Is there a way to force a type in Typescript?

0

Issue

I have this:

      const res: any = await table.find({}).toArray();
      const data: Type[] = res;

Is there a way to do something like this:

      const res: Type[] = await table.find({}).toArray();

without the error : Type 'Document[]' is not assignable to type 'Type[]'. ?

Solution

Check out Type Guards and Differentiating Types.

If you are sure that res always will be array of Type, you can force type using as:

const res = await table.find({}).toArray() as Type[]; // res: Type[] now

Answered By – Xeelley

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More