I'm trying to implement generic function. JS analog of this function is:
const getFactory = (field) => (value) => ({ [field]: value })
use case:
// types
type Field1 = { field1: string }
type Field2 = { field2: boolean }
type Field3 = { field3: number }
type Field4 = { field4: boolean }
type Type1 = Field1 | Field2 | Field4
type Type2 = Field2 | Field3 | Field4
// use case
const field1Factory = getFactory<Type1>('field1')
const field2Factory = getFactory<Type1>('field2')
const field4Factory = getFactory<Type1>('field4')
const anotherField2Factory = getFactory<Type2>('field2')
const field3Factory = getFactory<Type2>('field3')
const anotherField4Factory = getFactory<Type2>('field4')
const typeField1 = field1Factory('test') // { field1: 'test' }
const typeField2 = field2Factory(true) // { field2: true }
const typeField4 = field4Factory(false) // { field4: false }
const typeAnotherField2 = anotherField2Factory(false) // { field2: false }
const typeField3 = field3Factory(3) // { field3: 3 }
const typeAnotherField4 = anotherField4Factory(true) // { field4: true }
I supposed it maybe looks like this:
const getFactory = <Type extends {}>(field: keyof Type) => (value: Type[keyof Type]) => ({ [field]: value })
but when I trying to get factory (const field1Factory = getFactory('field1')) there is an Error:
Argument of type '"field1"' is not assignable to parameter of type 'never'.(2345)