Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Property 'xxx' does not exist on type 'string' when index signature has the property type

I’d appreciate some help on the following error.
I have an interface defined as:

export interface HandleOpenEvent {
  tooltipPayload: {
    dataKey: string;
    name: string;
    payload: {
      name: string;
      [id: string]: { title: string } | string;
    };
  }[];
}

Notice that I have title property defined. However, When I try to access the title property like this




const handleOpen = (e: HandleOpenEvent) => {
    const levelID = e.tooltipPayload[0].name;

    console.log(e.tooltipPayload[0].payload[levelID].title) //this throw the error below


    console.log(e.tooltipPayload[0].payload.name) //this works

I got an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Property 'title' does not exist on type 'string | { title: string; }'.
  Property 'title' does not exist on type 'string'.

I tried narrowing as suggested in some posts, but that did not fix the error.

//narrowing did not work here
   if (typeof e.tooltipPayload[0].payload[levelID] != "string") {
      setDetailKey(e.tooltipPayload[0].payload[levelID].title);
    }

I search on Stackoverflow and google with various keywords but couldn’t find a relevant explanation.

>Solution :

Try this:

const levelPayload = e.tooltipPayload[0].payload[levelID]
if(typeof levelPayload === 'object') {
   levelPayload.title
}

though if possible I’d suggest to rethink the ‘payload’ interface. For example maybe this could be better

type LevelId = string
interface Payload {
   name: string
   levels: Record<LevelId, Level>
}
interface Level {
   title: string
}

then there won’t be ambiguity and this won’t create type error

...payload.levels[levelId]?.title
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading