How to change type of a property that gets returned from a method

Viewed 25

So I have a method useGetAuthorizationWrapper() which returns { data: unknown } but the expected data that I'll get is an array.

So, when I use data.length I'm getting an error. Obviously, I'll get an error because it is of unknown type.

What I need is => I have to change my return type of data to an array. How can I modify it while calling useGetAuthorizationWrapper() method?

For example like this: useGetAuthorizationWrapper<{ data: [] }>(); // its not working

Under the wood useGetAuthorizationWrapper() calls useQuery() from react-query package

I have searched this issue on the web but didn't get a lead.

1 Answers

When receiving an unknown type you need to cast it:

const wrapper = useGetAuthorizationWrapper();
if (Array.isArray(wrapper.data)) { // just to be sure we have an array
  const data = wrapper.data as any[]; // cast unknown field
  // do your things
} else {
  // handle error
}

However, if possible, you can provide types to useQuery:

Related