Home > Enterprise >  Why 'string' cannot be used to index?
Why 'string' cannot be used to index?

Time:03-03

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;
};

CodePudding user response:

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

  • Related