I have the following interfaces:
interface ColDef<Entity, Field extends keyof Entity> {
field: Field;
valueGetter(value: Entity[Field], entity: Entity): any
}
interface Options<Entity> {
colDefs: ColDef<Entity, ??>[]
}
const options: Options<{ name: string }> = {
colDefs: [{
field: 'name',
valueGetter(value) {
// how do I make value typed as string??
}
}]
}
I want to infer the entity field type in the valueGetter
function. The issue is that I ColDef is required the key as the second generic, but I'm passing an array. How can I solve this?
CodePudding user response:
interface ColDef<Entity, Field extends keyof Entity> {
field: Field;
valueGetter(value: Entity[Field], entity: Entity): any
}
type A = {
name: string;
age: number;
}
interface Options<Entity> {
colDefs: { [K in keyof Entity]: ColDef<Entity, K> }[keyof Entity][]
}
type What = { [K in keyof A]: ColDef<A, K> }
// ^?
// type What = {
// name: ColDef<A, "name">;
// age: ColDef<A, "age">;
// }
type What1 = { [K in keyof A]: ColDef<A, K> }[keyof A]
// ^?
// type What1 = ColDef<A, "name"> | ColDef<A, "age">
const options: Options<A> = {
colDefs: [{
field: 'name',
valueGetter(value) {
// ^? (parameter) value: string
// how do I make value typed as string??
}
}]
}