I am facing challenges in satisfying the TypeScript compiler with my code.
I define a type that includes only optional fields, for example:
interface UserData {
email?: string;
phone?: string;
//...
}
and I have a reduction function that transforms some data into the format of UserData
:
type FieldValue = string | number | boolean;
interface RawData {
fieldName: string;
fieldValue: FieldValue;
}
function formatField(value: FieldValue): string {
// Format the value and return it as a string
return `formatted-${value}`;
}
function format(rawDataList: RawData[]): UserData {
return rawDataList.reduce<UserData>((userData, rawData) => {
// Compiler error - Type 'string' is not assignable to type 'undefined'
userData[rawData.fieldName as keyof UserData] = formatField(rawData.fieldValue);
return userData;
},
{}
);
Despite this, the field assignment consistently raises an issue stating
Type 'string' is not assignable to type 'undefined'
. What could be causing this problem?