Issue
This Content is from Stack Overflow. Question asked by Jason_Hough
So far no luck on this problem on this site. Someone who knows there stuff hopefully can help.
I have a type here :
type Person = {
value: string;
label: string;
};
And I have a block of code as promise here which gets the data from the api – then it transforms it to the correct type of array for the react component and then I hope to return it using the return command in a promise – like so :
const fetchDropDown = async () : Promise<Array<Person> | string> => {
try {
const stuff = await dynamicsWebApi.retrieveAll("accounts",["name"]);
const records = stuff.value;
const options = records?.map(d => ({
"value": d.name,
"label": d.name
}));
console.log(options)
return options
} catch (error) {
if (error) {
console.log(error)
}
}
}
But it is giving me all sorts of errors :
on the return options line
Type ‘{ value: any; label: any; }[] | undefined’ is not assignable to
type ‘string | Person[]’. Type ‘undefined’ is not assignable to type
‘string | Person[]’
I think it is because it is an array that I am passing back and the Person type is not an array, but I am the first to say I don’t know much about typescript.
Also on the react component itself it is error where I am putting the load options
<div>
<AsyncSelect
cacheOptions
defaultOptions
loadOptions={fetchDropDown}
/>
Any help Please!
Solution
Try this:
const fetchDropDown = async () : Promise<Array<Person> | undefined > => {
try {
const stuff = await dynamicsWebApi.retrieveAll("accounts",["name"]);
const records = stuff.value;
const options = records?.map(d => ({
"value": d.name,
"label": d.name
} as Person));
console.log(options)
return options
} catch (error) {
if (error) {
console.log(error)
}
}
}
This Question was asked in StackOverflow by Jason_Hough and Answered by PeterT It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.