Reputation: 5731
type MyStructure = Object[] | Object;
const myStructure: MyStructure = [{ foo: "bar" }];
myStructure.map(); // Property 'map' does not exist on type 'MyStructure'. any
The library either delivers an object or an array of this object. How can I type this?
EDIT
And how can I access properties like myStructure["foo"]
in case of myStructure
will be an object?
Upvotes: 26
Views: 86249
Reputation: 97
Add [] to the end of itemProps.
E.g.
const {
data: prescriptions,
isLoading: loadingPrescriptions,
}: UseQueryResult<PrescriptionProps[], Error> = useQuery<
PrescriptionProps[],
Error
>(
['patient', 'prescriptions', { patientId: itemId }],
() =>
fetchItem({
type: 'patients',
id: 'prescriptions',
query: { queryName: 'patientId', queryValue: itemId },
}),
{ enabled: !!itemId }
)
....
{prescriptions?.map( (prescription: PrescriptionProps) => (
Upvotes: 0
Reputation: 1268
In a similar case I saw map doesn't exist on type. I had the following code:
export interface Categories {
authors: {
_key: string
name: string
}[]
}
and then that was going to another interface
....
categories: Categories
The solution was to alter the main to contain just a single one as
categories: Category[]
with
export interface Category {
_key: string
name: string
}
Upvotes: 1
Reputation: 107
Even I faced this issue of 'Property 'map' does not exist on type Object' while I was trying to use .map() on non-iterable codes.. in my case I was using map on JSON object coming from an API to convert its keys i.e category into string[] but was constantly getting this error
JSON data coming from API -> {
{
id:1,
category:'cat-1'
},
{
id:2,
category:'cat-2'
}
}
Then I used the JSON methods as
objFromAPI = http.get('someUrl');
categoryList: string[] = JSON.parse(JSON.stringify(objFromAPI)).map(data => data.category);
And hence I was able to iterate on the parsed object as JSON methods converted it to an array
Upvotes: 1
Reputation: 250812
Because your type means you could have an object, or you could have an array; TypeScript can't determine which members are appropriate.
To test this out, change your type and you'll see the map
method is now available:
type MyStructure = Object[];
In your case, the actual solution will be to use a type guard to check that you have an array before attempting to use the map
method.
if (myStructure instanceof Array) {
myStructure.map((val, idx, []) => { });
}
You could also solve your problem using a slightly different definition of MyStructure
, for example:
type MyStructure = any[] | any;
Or the narrower:
class Test {
foo: string;
}
type MyStructure = Test[] | Test;
Upvotes: 42