Select to view content in your preferred language

Property "add doesn't exist in map" when trying to implment typescript with react

2172
2
Jump to solution
08-24-2021 09:44 AM
KenjooYeap
Occasional Contributor

I am trying to add typescript to the react code base that I have developed. Using the type "__esri.MapView" seems to have caused the following error, when trying to do "map.add" when trying to add layers to the view: 

"Property 'add' does not exist on type 'MapView | Map'. Property 'add' does not exist on type 'MapView'.

Am I using the wrong type here? Can someone point me to the right direction which type I should be using for MapView? 

Thanks! 

 

0 Kudos
1 Solution

Accepted Solutions
ReneRubalcava
Honored Contributor

If I understand, in your code you have something where it looks like this maybe?

function addToMap(target: MapView | Map) {
  // this is what you are trying to do
  // target.add(layer)
  // but you need to let TypeScript know what type it should expect.
  // you can do something like this, I haven't tested
  if (!Boolean(target.container)) {
    // should work because container is not on Map
    // but is on MapView
    // now TS knows what it is using
    target.add(layer);
  }
}

 

That might help, if not, do have a reproducible sample of the issue.

View solution in original post

0 Kudos
2 Replies
ReneRubalcava
Honored Contributor

If I understand, in your code you have something where it looks like this maybe?

function addToMap(target: MapView | Map) {
  // this is what you are trying to do
  // target.add(layer)
  // but you need to let TypeScript know what type it should expect.
  // you can do something like this, I haven't tested
  if (!Boolean(target.container)) {
    // should work because container is not on Map
    // but is on MapView
    // now TS knows what it is using
    target.add(layer);
  }
}

 

That might help, if not, do have a reproducible sample of the issue.

0 Kudos
KenjooYeap
Occasional Contributor

Thanks for the hint, my function was returning two possible types and I have to cast it to a tuple so that it's assigned to the right type. 

0 Kudos