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:
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?
CodePudding user response:
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
}