I get the message Property 'map' does not exist on type 'string | string[]'.
:
const data = [
['1', ['11']],
['2', ['21']],
['3', ['31']],
]
data.map(topic => {
topic[1].map(p => console.log(p))
})
What can I do to solve this (the error message, code works as expected)?
This is within an Astro project, JavaScript (no TypeScript), in case this is relevant.
3
Answers
Why that happens?
Typescript looks to the array
['1', ['11']]
and infers the type as(string | string[])[]
..map
exists in arrays but not in the string.To fix that:
as const
at the end of the array..map
method check the type:data
is inferred as(string | string[])[][]
per default by the TypeScript compiler. That type is not specific enough to call an array method such as.map()
on an item because for TypeScript any item in thedata
array could either be astring
or astring[]
.What you’ll have to do is specifying the type of
data
in more detail. You can either do that with an Explicit Type Annotation…… or by using an
const
-assertion. That way TypeScript will use the narrowest possible type for your variable.As the other answers already pointed out, if you can change the file to TypeScript, you can explicitly type data:
If you need your file to remain in JavaScript, you can still explicitly type data, by using JSDoc syntax, which is recognized by most IDEs.