Question
Type return of a function depending of a parameters as a part of the returning object
I'm facing a issue I don't know if it's possible to resolve.
function getOptions(
period: { first: string; last: string },
prefix?: string
){
if (prefix) {
return {
[`${prefix}_first`]: formatDay(period.first),
[`${prefix}_last`]: formatDay(period.last),
[`${prefix}_month`]: format(new Date(), 'MMMM', {
locale: i18n.t('datefns:format', { returnObjects: true }),
}),
}
}
return {
first: formatDay(period.first),
last: formatDay(period.last),
month: format(new Date(), 'MMMM', {
locale: i18n.t('datefns:format', { returnObjects: true }),
}),
}
}
I would like typescript return the right typed object in function of the prefix parameter. How can I do it ?
The expected result is
getOptions({first: '01', last: '10'}) // {first: string, last: string, month: string}
getOptions({first: '01', last: '10'}, 'christmas') // {christmas_first: string, christmas_last: string, christmas_month: string}