I'm trying to define an array of fields for a form, where each item may have a different type. I've defined these types:
interface FormData{
value1:number
value2:number|null
value3:string
value4:boolean
}
interface Field<T,K extends keyof T,TV=T[K]>{
key:K&string
value:TV
validation?:(value:TV)=>boolean
}
Defining an individual field works fine:
const field:Field<FormData,'value1'>={
key:'value1',
value:1,
validation(value:number):boolean{
return value<3
}
}
But when defining an array for several items, like this:
const fields:Field<FormData,keyof FormData>[]=[
{
key:'value1',
value:1,
validation(value:number):boolean{
return value<3
}
},
{
key:'value3',
value:'xxx',
validation(value:string):boolean{
return value!=='xxx'
}
}
]
TypeScript is:
- Allowing
value
be of any type, as long as it'snumber|null|string|undefined
(eg a string forvalue1
) - Complaining about the
validation()
functions, since they don't acceptnumber|null|string|undefined
as a parameter
Is there a way to help TS infer the correct type of each item within the array? Ideally, I'd also would like to define the array as Field<FormData>[]
.
I'm using TypeScript 4.3.