I'm a beginner in TypeScript, and I'm not sure why TS is complaining on the left hand side of the = sign.
const nonMandatoryFields = [
'address',
'mobilePhone',
'postCode',
'state',
'suburb',
'testMode',
];
interface XeroClientData {
address: string;
firstName: string;
lastName: string;
suburb: string;
postCode: string;
state: string;
country: string;
mobilePhone: string;
email: string;
recordId: string;
testMode: boolean;
}
const sanitiseFields = (fields: XeroClientData) => {
for (const key of nonMandatoryFields) {
// Error on the left hand side
// Element implicitly has an 'any' type
// because expression of type 'string' can't be used to index type 'XeroClientData'
fields[key] = fields[key as keyof XeroClientData]
? fields[key as keyof XeroClientData]
: '';
}
return fields;
};
As you can see, I've tried the keyof operator and it worked fine on the right side.
If somebody could please point me to a reference doc or point out the problem - would greatly appreciate it. Thanks!
EDIT: Have managed to fix the issue thanks to @jcalz (BIG THANKS!). See below:
const nonMandatoryFields = [
'address',
'mobilePhone',
'postCode',
'state',
'suburb',
] as const;
type NonMandatoryField = typeof nonMandatoryFields[number];
interface XeroClientData {
address: string;
firstName: string;
lastName: string;
suburb: string;
postCode: string;
state: string;
country: string;
mobilePhone: string;
email: string;
recordId: string;
testMode?: boolean; // optional property
}
const sanitiseFields = (fields: XeroClientData) => {
nonMandatoryFields.forEach(<K extends NonMandatoryField>(key: K) => {
fields[key] = fields[key] ? fields[key] : '';
});
return fields;
};
SomeInterfaceandnoMandatoryFieldsare, so it's hard to know how to advise you. If you do make such an edit and want me to take another look, please mention @jcalz in a comment so that I'm notified.""to abooleanproperty. That's an error for a good reason. What are you actually trying to do there?