Consider the following TypeScript definition:
interface Configuration {
field: string
}
function bar<T extends Configuration>(arr: T[]): Record<T['field'], undefined>
function bar(arr: Configuration[]): Record<string, undefined> {
const object = {}
_.forEach(arr, item => {
object[item.field] = undefined
})
return object
}
const outcome = bar([{field: 'example'}])
outcome.test // This should prompt an error as the array argument does not include an object with a field of "test".
The code above was inspired by Dynamically generate return type based on parameter in TypeScript, although my scenario involves an array of objects rather than an array of strings.
The issue lies in the fact that the type of outcome
is Record<string, undefined>
when I intend it to be
Record<'example', undefined>
. It seems that my return type declaration of Record<T['field'], undefined>
may be incorrect (as T
represents an array of objects similar to Configuration
) but finding the correct specification for this generic type has proven challenging.
Any assistance on this matter would be greatly appreciated.