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

Type 'string' is not assignable to type 'keyof CustomerInput'

I know this question was asked multiple times but at this point, I feel like this error could show up in multiple cases and I can’t find the answer to this problem.

Here is the type that I have:

export type CustomerInput = {
  email: string;
  firstName?: string;
  lastName?: string;
  phone?: string;
  id?: string;
  locale?: string;
  tags?: string;
  metafields?: Array<MetafieldInput>;
  acceptsMarketing?: boolean;
  acceptsMarketingUpdatedAt?: string;
  marketingOptInLevel?: CustomerMarketingOptInLevel;
  addresses?: Array<AddressInput>;
  note?: string;
  privateMetafields?: Array<PrivateMetafieldInput>;
  smsMarketingConsent?: CustomerSmsMarketingConsentInput;
  taxExempt?: boolean;
  taxExemptions?: Array<string>;
};

I am trying to map other type to return object: CustomerInput like so:

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

  const customerInput: CustomerInput = {
    email: ''
  };

  Object.keys(row).forEach((property: string) => {

    let propValue = row[property as keyof ExcelRow] as boolean | string;
  
    if (propValue === 'false') {
      propValue = false;
    } else if (propValue === 'true') {
      propValue = true;
    }

    // ...

    if (property && property.startsWith('CustomerInput.')) {
      // Type 'string' is not assignable to type 'keyof CustomerInput'
      const customerProperty: keyof CustomerInput = property.replace('CustomerInput.', '');
      if (customerProperty.length > 0 && customerProperty) {
        // Type 'string | boolean' is not assignable to type 'never'.
        // Type 'string' is not assignable to type 'never'.ts(2322)
        customerInput[customerProperty] = propValue;
      } 
    }
  });

What am I doing wrong?

>Solution :

replace returns string type, you cannot assert a string to be keyof CustomerInput. If you know that string replacement will return CustomerInput key certainly, you can cast it by as like below:

const customerProperty: keyof CustomerInput = property.replace('CustomerInput.', '') as keyof CustomerInput

For the second case, you can reassign the object instead of direct value assignment

customerInput = {
    ...customerInput,
    [customerProperty]: propValue
  }

Playground

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