Search code examples
typescriptinterface

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:

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