The expected result on input:
const MOCK_DATA = {
role: {
option: 'Founder / CEO',
text: '',
},
content: {
option: 'Marketing videos',
text: '',
},
};
getSurveyData(MOCK_DATA)
// {
// role: string;
// content: string;
// }
The expected result on some other input:
const MOCK_DATA2 = {
position: {
option: ['Founder / CEO', 'Developer'],
text: '',
},
termsConsent: true,
};
getSurveyData(MOCK_DATA2)
// {
// position: string;
// termsConsent: boolean;
// }
The approach I devised does not infer the return type accurately, so how can a generic function be created to correctly infer the return type based on the input value?
The top-level key in the input can be of type
string | object | boolean | number
.
Actual return type:
const surveyData: {
[x: string]: string | boolean | number;
}
Code:
type FormValues = {
[key: string]:
| {
option: string | string[];
text: string;
}
| boolean
| string
| number
};
export const getSurveyData = (formValues: FormValues) => {
return Object.entries(formValues).reduce(
(
prev: {
[key: string]: string | boolean | number;
},
[key, data],
) => {
let value: string | boolean | number = '';
if (data instanceof Object) {
if (Array.isArray(data.option)) {
value = data.option.join(', ');
} else {
value = data.option;
}
}
if (typeof data === 'boolean' || typeof data === 'string' || typeof data === 'number') {
value = data;
}
return { ...prev, [key]: value };
},
{},
);
};
Here's TS playground