I'm trying to set a generic selector function for one of my reusable component. The goal of this function is to return a string or number value from an object that is passed as an argument.
The function signature is defined as follows:
type ComponentProps{
selector: <T>(row: T) => string | number
// ...
}
Used inside of the component:
export const data = [
{
name: "John Doe",
age: 30,
job: "Software Engineer",
pets: {
dogs: 1,
cats: 2,
turtles: 0,
}
}
// ...
]
export type Pets = { dogs: number; cats: number; turtles: number }
export type Gender = "male" | "female" | "undisclosed"
export type Person = {
name: string
age: number
job: string
pets: Pets
gender: Gender
}
// ...
<MyComponentName someProps={/* ... */} selector={ (row: Person) => row.name } />
The error I get is as follow:
Type '(row: Person) => string' is not assignable to type '<T>(row: T) => string | number'.
I also tried to modify my argument type inside of my component to :
(row: object) => row.name
but then i get an error stating that the name
property is not defined on the object.
How could I modify my function signature so it can receive any object as an argument as long as the function returns a string or a number?
This seems like a pretty standard thing to do but I cannot wrap my head around it.