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

Why 'string' cannot be used to index?

Do you know why I got this error?

[tsl] ERROR in /Applications/MAMP/htdocs/wp-content/plugins/tikex/tikexModule/components/PartnerAndDeliveryForm.tsx(58,12)
      TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ partnerData?: NameAndAddress | undefined; deliveryData?: NameAndAddress | undefined; businessUseApproval?: boolean | undefined; email?: string | undefined; error?: string | undefined; }'.
  No index signature with a parameter of type 'string' was found on type '{ partnerData?: NameAndAddress | undefined; deliveryData?: NameAndAddress | undefined; businessUseApproval?: boolean | undefined; email?: string | undefined; error?: string | undefined; }'.
  const setData = (key1: string, key2: string, value: string) => {
    let partnerAndDeliveryData2 = {
      ...partnerAndDeliveryData,
    };
    if (key2) {
      if (!partnerAndDeliveryData2?.[key1]) { // <--- here
        partnerAndDeliveryData2?.[key1] = {};

Following types are used:

export type SetPartnerAndDeliveryDataIn = {
  partnerData?: NameAndAddress;
  deliveryData?: NameAndAddress;
  businessUseApproval?: boolean;
  email?: string;
  error?: string;
};

export type NameAndAddress = {
  name?: string;
  phoneNumber?: string;
  country?: string;
  postalCode?: string;
  city?: string;
  address?: string;
  taxCode?: string;
};

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

>Solution :

You can change the type of key1 to the following to resolve the problem

const setData = (key1: keyof SetPartnerAndDeliveryDataIn, key2: string, value: string) => {

This way key1 is not going to be a string, but a key of the type SetPartnerAndDeliveryDataIn

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