Reputation: 1332
I am attempting to use the .map() function over an array in Typescript.
I run the following code:
Promisefunction().then((data : [{item: String}]) => {
data.map((Object) => {
console.log(Object.attribute)
})
})
In the console, I get the expected result and it seems to work fine but then the program crashes and I get the following error:
Unhandled Rejection (TypeError): Cannot read property 'map' of undefined
I assume this is because Typescript doesn't know Data is an array, yet I have established that up above. So I am left confused.
Any help would be appreciated, thank you.
**Edit 1: Added body of promisefunction **
export default function promiseFunction(){
return new Promise<any[]>(function(resolve, reject){
const { data, loading, error, fetchMore } = useQuery(
QUERY,
{
variables: {
first: 15,
offset: 0
},
errorPolicy: 'all'
});
if(data){
resolve(data.getData);
}
else if(error){
reject("broke");
}
})
}
Upvotes: 0
Views: 360
Reputation: 84912
That error is happening at runtime, not compile time. So typescript is not really involved. The promise returned by Promisefunction
is apparently not resolving to an array. Typescript won't know about this, since it only knows the information you provide to it at compile time, and that information is apparently flawed. If you can share the code for Promisefunction, we may be able to diagnose it.
EDIT: With your latest updates, there is more of an indication of what's wrong, but also several new problems. You are attempting to use a react hook inside of an arbitrary function. This is not supported. Hooks can only be used inside of functional components and inside of other hooks.
So your code is running, then calling useQuery in a context where it is not meant to be called. Use query returns a data object with no data in it, and you resolve your promise with undefined. You may have told typescript that it's a Promise<any[]>
, but that was incorrect. Since you've given typescript incorrect information, it will assume that incorrect information from then on, leading to it not being able to point out your problem when you try to do data.map
It's hard for me to recommend a course of action to you because you seem to be misusing the tools at hand. I don't understand why you would be wanting to wrap a hook in a promise in the first place.
Upvotes: 3
Reputation: 1647
TypeScript cannot contextually determine what the Promise resolves to (see:this) therefore you have to assert it.
Something like:
function getARPTable() {
return new Promise<any[]>((resolve, reject) => {
arp.table((error, devices) => {
if (error) reject(error);
else resolve(devices);
});
});
}
Upvotes: 1